Plural for fields_for has_many association not showing in view

8bithero picture 8bithero · Oct 20, 2012 · Viewed 11.1k times · Source

Currently, an Item belongs_to a Company and has_many ItemVariants.

I'm trying to use nested fields_for to add ItemVariant fields through the Item form, however using :item_variants does not display the form. It is only displayed when I use the singular.

I have check my associations and they seem to be correct, could it possibly have something to do with item being nested under Company, or am I missing something else?

Thanks in advance.

Note: Irrelevant code has been omitted from the snippets below.

EDIT: Don't know if this is relevant, but I'm using CanCan for Authentication.

routes.rb

resources :companies do
  resources :items
end

item.rb

class Item < ActiveRecord::Base
  attr_accessible :name, :sku, :item_type, :comments, :item_variants_attributes


  # Associations
  #-----------------------------------------------------------------------
  belongs_to :company
  belongs_to :item_type
  has_many   :item_variants

  accepts_nested_attributes_for :item_variants, allow_destroy: true

end

item_variant.rb

class ItemVariant < ActiveRecord::Base
  attr_accessible :item_id, :location_id

  # Associations
  #-----------------------------------------------------------------------
  belongs_to :item

end

item/new.html.erb

<%= form_for [@company, @item] do |f| %>
  ...
  ...
  <%= f.fields_for :item_variants do |builder| %>
    <fieldset>
      <%= builder.label :location_id %>
      <%= builder.collection_select :location_id, @company.locations.order(:name), :id, :name, :include_blank => true %>
    </fieldset>
  <% end %>
  ...
  ...
<% end %>

Answer

rewritten picture rewritten · Oct 20, 2012

You should prepopulate @item.item_variants with some data:

def new # in the ItemController
  ...
  @item = Item.new
  3.times { @item.item_variants.build }
  ...
end

Source: http://rubysource.com/complex-rails-forms-with-nested-attributes/