如果值为空,获取要显示的文本 ruby 4 未定义的方法 `first_name'

Get text to display if value is blank ruby 4 undefined method `first_name'

我是 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/
    Tenant: #{@house.tenant.first_name} #{@house.tenant.last_name}

当数据库在 HOUSES 模型中保存 tenant_id 的值时,它显示正常,但是当 HOUSE 记录的租户 ID 为 nil 时,我得到以下错误。

显示 C:/Sites/landlord2/app/views/houses/show.html.haml 其中第 8 行提出:

nil:NilClass.

的未定义方法“first_name”

in show 反正有改的吗

Tenant: #{@house.tenant.first_name} #{@house.tenant.last_name}

所以如果 tenant_id 是空白的,它可以显示一些文本?

谢谢

哎呀,你问一下就可以了if @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'

就个人而言,我不太喜欢用模板逻辑填充视图。

这可能是使用辅助方法的好地方。

在您的 house_helper.rb 文件中,尝试制作一个看起来像这样的 current_tenant 方法。

  def current_tenant(house)
    if house.tenant 
      "#{house.tenant.first_name} #{house.tenant.last_name}"
    else
      "Vacant"
    end
  end

另外,显示租户的全名之类的事情可能是您经常做的事情。因此,最好在您的租户模型上添加一个 full_name 方法,以便您可以重用它。

  class Tenant
    ...
    def full_name
      "#{first_name} #{last_name}"
    end
    ...
  end

这样,您可以将辅助方法清理成如下简单的内容:

  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)}