获取要显示的文本,如果值是空白红宝石4未定义的方法`如first_name”

问题描述 投票:1回答:2

我对导轨一个新手,所以请您耐心等待

目前,这是我的节目页面在我的意见的文件夹屋

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

它显示罚款时,该数据库保存在房屋模型tenant_id的值,但是当租户ID是零一所房子的记录,我得到下面的错误。

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

未定义的方法`如first_name”的零:NilClass。

在节目反正是有变化

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

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

谢谢

ruby-on-rails ruby ruby-on-rails-4 haml
2个回答
1
投票

干草,你可以问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'

1
投票

就个人而言,我不填充了模板的逻辑视图的大风扇。

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

在你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)}
© www.soinside.com 2019 - 2024. All rights reserved.