轨道:二级关联/未定义的方法错误



>我有这些方法:

class Item < ApplicationRecord
  has_many :fabrics
end
class Fabric < ApplicationRecord
  belongs_to :item
  has_many :inventories
end
class Inventory < ApplicationRecord
  belongs_to :fabric
end

控制器:

class InventoryController < ApplicationController
def index
  @inventory = Inventory.all
end

并查看:

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

我收到此错误:

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

有人可以解释为什么我会收到此错误吗?是因为范围吗?我已阅读活动记录关联指南 (http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference(。在"4.1.3.2 包含"下,有一个类似于我的模型关联的示例,它说这应该没问题吗?

此错误意味着某些库存没有相关的结构等inventory.fabric == nil。您需要在视图代码中管理这种情况:

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

最新更新