Ruby索引页显示,即使为nil,当前也会出现未定义的错误

时间:2019-02-05 20:56:13

标签: ruby ruby-on-rails-4

您好,我正在尝试获取我的房地产索引页,以显示当前物业中有哪些租户。

通过执行以下操作

,它可以在show.html页面上运行
    .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= 'No Tenant Assigned'

我该如何为我的索引页面采用相同的方法,这就是我目前所拥有的,但是我得到未定义的错误“承租人”。

.wrapper_with_padding
  #houses.clearfix
    - unless @houses.blank?
      - @houses.each do |house|
        %a{ href: (url_for [house])}
          .house
            %p.title= house.title
            %p.postcode= 'Postcode: ' + (house.postcode)
            %p.price= number_to_currency(house.price, :unit => "£") + ' per month'
            -if @house.tenant.present?
              %p.tenant_id= @house.tenant.first_name
            -else
              %p No Tenant Assigned
    - else
      %h2 Add a Property
      %p It appears you have not added any property's

    %button= link_to "New Property", new_house_path

这是完整的堆栈跟踪

Showing C:/Sites/landlord2/app/views/houses/index.html.haml where line #10 raised:

undefined method `tenant' for nil:NilClass
Rails.root: C:/Sites/landlord2

Application Trace | Framework Trace | Full Trace
app/views/houses/index.html.haml:10:in `block in _app_views_houses_index_html_haml__260246869_75400416'
app/views/houses/index.html.haml:4:in `_app_views_houses_index_html_haml__260246869_75400416'

1 个答案:

答案 0 :(得分:0)

这应该有效:

.wrapper_with_padding
  #houses.clearfix
    - unless @houses.blank?
      - @houses.each do |house|
        %a{ href: (url_for [house])}
          .house
            %p.title= house.title
            %p.postcode= 'Postcode: ' + (house.postcode)
            %p.price= number_to_currency(house.price, :unit => "£") + ' per month'
            -if house.tenant.present?
              %p.tenant_id= house.tenant.first_name
            -else
              %p No Tenant Assigned
    - else
      %h2 Add a Property
      %p It appears you have not added any property's

    %button= link_to "New Property", new_house_path

请注意,尽管我没有解决其他任何错误,但您可能应该阅读有关Haml规范的一些信息。

您不必做%p= 'No Tenant Assigned',因为%p No Tenant Assigned有用。