0
我有以下方法:Rails的:二級協會/未定義的方法錯誤
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包含'下,有一個類似於我的模型關聯的例子,它說這應該沒問題?
謝謝!我在rails控制檯中運行Inventory.where(fabric_id:nil),並發現了一個fabric_id == nil的記錄!我破壞了那條記錄,現在一切正常!謝謝伊利亞! – Chupakraw