Reputation: 2672
Consider i have two tables namely Item and color.
The Item table contains has_many relationship with colour as each items can have more than one color but the colors are not already present.
I have a page where i have to add items and in the same page i have to specify the colors for the item. so how can i add those values to the color table along with item id. Please help me. I am struggling to move.
EDIT:
Item model
class Item < ActiveRecord::Base
has_many :colors
end
Color model
class Color < ActiveRecord::Base
belongs_to :items
end
table
id | created_at | updated_at | item_id | color_name
----+------------+------------+---------+--------------
Upvotes: 0
Views: 220
Reputation: 3083
If the colors will always be created with item then you need to use nested attributes.
class Item < ActiveRecord::Base
attr_accessible :colors_attributes
has_many :colors
accepts_attributes_for :colors
end
In your controller action Items#new
@items.colors.build
In your items/new.html.erb add the fields_for with the other fields of items table.
<%= form_for @item do |f| %>
<%= f.text_field :name %>
...
<%= f.fields_for :colors do |color| %>
<%= color.text_field :some_column_name_from_color %>
<% end %>
<% end %>
For adding/removing multiple colors on the fly you can use nested_form gem
Upvotes: 1