Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plural for fields_for has_many association not showing in view

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 %>
like image 934
8bithero Avatar asked Oct 20 '12 11:10

8bithero


2 Answers

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/

like image 153
rewritten Avatar answered Oct 22 '22 11:10

rewritten


try this way

in your item controller new action write

def new
  ...
    @item = # define item here
    @item.item_variants.build if @item.item_variants.nil?
  ...
end

and in item/new.html.erb

<%= form_for @item do |f| %>
  ...
  ...
  <%= f.fields_for :item_variants do |builder| %>
    ...
  <% end %>
  ...
  ...
<% end %>

for more see video - Nested Model Form

like image 35
Dipak Panchal Avatar answered Oct 22 '22 12:10

Dipak Panchal