简体   繁体   中英

Rails: second-level associations/undefined method error

I have these methods:

class Item < ApplicationRecord
  has_many :fabrics
end

class Fabric < ApplicationRecord
  belongs_to :item
  has_many :inventories
end

class Inventory < ApplicationRecord
  belongs_to :fabric
end

Controller:

class InventoryController < ApplicationController

def index
  @inventory = Inventory.all
end

And view:

<% @inventory.each do |f| %>
    <tr>
        <td><%= f.fabric.item %></td>
    </tr>
<% end %>

I get this error:

ActionView::Template::Error (undefined method `item' for nil:NilClass):

Can someone explain why I am getting this error? Is it because of scopes? I've read Active Record Associations Guide ( http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference ). Under '4.1.3.2 includes' there is an example similar to my model associations which says this should be fine?

This error means that some of the inventories does not have related fabric, etc inventory.fabric == nil . You need to manage this case in the view code:

<% @inventory.each do |f| %>
    <tr>
        <td><%= f.fabric ? f.fabric.item : "Without item" %></td>
    </tr>
<% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM