Rails 未定义方法 `build' for nil:NilClass

Dil*_*eet 0 ruby-on-rails

我正在尝试创建一个接受来自另一个模型的嵌套属性的表单。但是在控制器的新函数中,我正在运行 @item.item_type.build 并收到此错误

undefined method `build' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

这是 items_controller 中的新功能

  def new
    @item = Item.new
    @item_gallery = @item.item_galleries.build
    @item_type = @item.item_type.build
  end
Run Code Online (Sandbox Code Playgroud)

参数:

def item_params
  params.require(:item).permit(:title, :price, :description, item_galleries_attributes: [:id, :item_id, :image], item_type_attributes: [:id, :type, :item_id])
end
Run Code Online (Sandbox Code Playgroud)

在 item.rb(模型)文件中:

  has_many :item_galleries, dependent: :destroy
  has_one :item_type
  accepts_nested_attributes_for :item_galleries
  accepts_nested_attributes_for :item_type
Run Code Online (Sandbox Code Playgroud)

我基本上是在尝试从表单下拉列表中设置项目类型。

例子:

<%= f.fields_for :item_types do |t| %>
  <%= t.label :type %>
  <%= t.select :type, options_for_select(["Type1", "Type2", "Type3"]), prompt: "Select One" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

这个想法是最终根据 item_type 过滤项目

mar*_*rgo 5

对于 has_one 关联,您使用 build_association 方法而不是 association.build 方法。有关更多信息,请参阅文档,http://guides.rubyonrails.org/association_basics.html#the-has-one-association

@item_type = @item.build_item_type
Run Code Online (Sandbox Code Playgroud)