I have a form used to create a ‘Style’. The style may have any number of
‘features’ which correspond to ‘Feature’ models in the features table. I
would like to add the appropriate entries to a relationship table
(‘stylefeatures’) whenever a Style is created. Here is a breakdown of my
models:
class Style < ActiveRecord::Base
has_many :stylefeatures
has_many :features, :through => :stylefeatures, :foreign_key =>
:feature_id
accepts_nested_attributes_for :stylefeatures
end
class Feature < ActiveRecord::Base
has_many :stylefeatures
has_many :styles, :through => :stylefeatures, :foreign_key =>
:style_id
end
class Stylefeature < ActiveRecord::Base
belongs_to :style
belongs_to :feature
accepts_nested_attributes_for :features
end
…and here is my controller for the ‘new’ action:
def new
@style = Style.new
@features = Feature.all
end
…and here is my form:
<%= simple_form_for @style, :html => { :class => ‘form-horizontal’ } do
|m| %>
<%= m.simple_fields_for :features do |p| %>
<%= p.input :name, :label => "Features", :collection => @features,
:input_html => { :multiple => true } %>
<% end %>
[…]
<% end %>
Right, so the list of features DOES load up into the multiple select box
within my form. So that’s sweet. However, when I go to submit I receive
the
error: No association found for name ‘features’. Has it been defined
yet?
I get the exact same error when adding @style.features.build to the
controller ‘new’ action.
This is what the params hash looks like. It carries the ID of the
feature
name selected.
“features”=>{“name”=>["",“7”]}
So my question is, how do I go about loading the features listed in the
features table for the nested form, and on form submission, handle the
selected features for addition to the stylefeatures relationship table.
Thanks very much