Dileet
Dileet

Reputation: 2064

Rails undefined method `build' for nil:NilClass

I'm trying to created a form that accepts nested attributes from another model. But in the new function in the controller I'm running @item.item_type.build and get this error

undefined method `build' for nil:NilClass

this is the new function in the items_controller

  def new
    @item = Item.new
    @item_gallery = @item.item_galleries.build
    @item_type = @item.item_type.build
  end

Params:

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

and inside the item.rb (model) file:

  has_many :item_galleries, dependent: :destroy
  has_one :item_type
  accepts_nested_attributes_for :item_galleries
  accepts_nested_attributes_for :item_type

I'm basically trying to set the item type from a form dropdown.

Example:

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

The idea is to eventually filter the items based on item_type

Upvotes: 0

Views: 1529

Answers (1)

margo
margo

Reputation: 2927

For a has_one association you use the build_association method as opposed to the association.build method. Refer to the docs for more information, http://guides.rubyonrails.org/association_basics.html#the-has-one-association

@item_type = @item.build_item_type

Upvotes: 6

Related Questions