Ruby on rails 如果值为空,则获取要显示的文本ruby 4 undefined method`first#u name';
我是rails的新手,所以请注意 目前,这是“我的视图”文件夹中房屋的“显示”页面Ruby on rails 如果值为空,则获取要显示的文本ruby 4 undefined method`first#u name';,ruby-on-rails,ruby,ruby-on-rails-4,haml,Ruby On Rails,Ruby,Ruby On Rails 4,Haml,我是rails的新手,所以请注意 目前,这是“我的视图”文件夹中房屋的“显示”页面 .wrapper_with_padding #house.show %h1= @house.title %p= number_to_currency(@house.price, :unit => "£") %p= simple_format(@house.description) Occupied: #{@house.occupied} %br/ Tenan
.wrapper_with_padding
#house.show
%h1= @house.title
%p= number_to_currency(@house.price, :unit => "£")
%p= simple_format(@house.description)
Occupied: #{@house.occupied}
%br/
Tenant: #{@house.tenant.first_name} #{@house.tenant.last_name}
当db在HOUSES模型中为tenant_id保留一个值时,它显示良好,但当HOUSE记录的tenant id为nil时,我得到以下错误
显示C:/Sites/landord2/app/views/houses/show.html.haml,其中第8行出现:
nil:NilClass的未定义方法“first_name”
在表演中,还有什么需要改变的吗
Tenant: #{@house.tenant.first_name} #{@house.tenant.last_name}
如果租户id为空,它可以显示一些文本
谢谢Hay,您只需询问
如果@house.tenant.present?
,如果没有显示所需的文本,如以下代码:
.wrapper_with_padding
#house.show
%h1= @house.title
%p= number_to_currency(@house.price, :unit => "£")
%p= simple_format(@house.description)
Occupied: #{@house.occupied}
%br/
-if @house.tenant.present?
Tenant: #{@house.tenant.first_name} #{@house.tenant.last_name}
-else
%p= 'Text to display if tenant is blank'
就个人而言,我不太喜欢用模板逻辑填充视图 这可能是使用helper方法的好地方 在house\u helper.rb文件中,尝试创建一个类似以下内容的
当前\u租户
方法
def current_tenant(house)
if house.tenant
"#{house.tenant.first_name} #{house.tenant.last_name}"
else
"Vacant"
end
end
此外,你可能经常做一些事情,比如显示租户的全名。因此,最好在租户模型上添加全名
方法,以便重用它
class Tenant
...
def full_name
"#{first_name} #{last_name}"
end
...
end
通过这种方式,您可以将helper方法清理为如下简单内容:
def current_tenant(house)
return "Vacant" unless house.tenant
house.tenant.full_name
end
您的视图也会被清理到:
.wrapper_with_padding
#house.show
%h1= @house.title
%p= number_to_currency(@house.price, :unit => "£")
%p= simple_format(@house.description)
Occupied: #{@house.occupied}
%br/
Tenant: #{current_tenant(@house)}
我能问一下如何在我的索引页上使用这个吗?目前我有%p.tenant\u id=@house.tenant.first\u name您在索引页上有相同的问题吗?