【问题标题】:Rails: second-level associations/undefined method errorRails:二级关联/未定义方法错误
【发布时间】:2017-05-14 02:42:12
【问题描述】:

我有这些方法:

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):

谁能解释我为什么会收到这个错误?是因为范围吗?我已经阅读了 Active Record 关联指南 (http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference)。在“4.1.3.2 包含”下有一个类似于我的模型关联的示例,它说这应该没问题?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord model-associations


    【解决方案1】:

    此错误表示部分库存没有相关面料等inventory.fabric == nil。您需要在视图代码中管理这种情况:

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

    【讨论】:

    • 谢谢!我在 Rails 控制台中运行了 Inventory.where(fabric_id: nil) 并找到了一个带有 fabric_id == nil 的记录!我销毁了那个记录,现在一切正常!谢谢伊利亚!
    猜你喜欢
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    相关资源
    最近更新 更多