I have a form for creating a Style. When creating the style the user must also choose some features for the style.
The features are pre-populated into a multi-select box inside the form. When the style is saved the through table should be updated with entries (with style_id and feature_id) for each feature selected on the form.
I have in my controller:
def new
@style = Style.new
@style.stylefeatures.build
end
def create
@style = Style.new(params[:style])
@style.stylefeatures.build
@style.save
end
…and in my style model
attr_accessible :stylefeatures_attributes
has_many :stylefeatures
has_many :features, :through => :stylefeatures, :foreign_key => :feature_id
accepts_nested_attributes_for :stylefeatures
… and in my stylefeature model
belongs_to :style
belongs_to :feature
accepts_nested_attributes_for :feature
… and in my feature model
attr_accessible :description, :fullname, :name
has_many :stylefeatures
has_many :styles, :through => :stylefeatures, :foreign_key => :style_id
… and in my create form
<%= m.simple_fields_for :stylefeatures do |p| %>
<%= p.input :feature_id, :label => "Features", :collection => Feature.all, :input_html => { :multiple => true } %>
<% end %>
Now when I save the new Style, the stylefeatures table is updated with the appropriate style_id, but with two useless entries. The first is an array with all of the feature ids which have been selected in the form. The second is a blank entry with the appropriate style_id and nothing in the feature_id column.
Do you have any clue of what I might be doing wrong, or how to spread the collected feature_id’s into the table as desired?
in new action u r building only one stylefeature, so only one will be created with feature_id = ‘1,3,45,563’ (ofc depends that features u selected)
second one is generated by
@style.stylefeatures.buildin create actionu can try to remove fields_for and simply use :feature_ids instead of :feature_id
or