In my company form, I would like to be able to add products directly. Basically, a company can have many products.
class Company < ActiveRecord::Base
has_many :company_products
has_many :products, :through => :company_products
accepts_nested_attributes_for :products, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
end
My Form:
<%= form_for(@company) do |f| %>
<ul>
<li class="clearfix">
<%= f.label :company_name %>
<%= f.text_field :company_name %>
</li>
<li>
<%= f.collection_select :product_ids, Product.all, :id, :name, { :prompt => 'Select a product' } %>
</li>
<li>
<%= f.collection_select :product_ids, Product.all, :id, :name, { :prompt => 'Select a product' } %>
</li>
<li>
<%= f.collection_select :product_ids, Product.all, :id, :name, { :prompt => 'Select a product' } %>
</li>
....
Above, does not exactly work. Since it only adds the product that was selected in the last f.collection开发者_StackOverflow_select
.
This is what I am trying to achieve. In console, I do:
company.update_attributes({"product_ids"=>["1", "2", "3"]})
Which would assign products with id: 1, 2 and 3 to the specified company.
What is the proper way to do this in Rails 3?
EDIT
In my form, it works with:
<%= f.collection_select :product_ids, Product.all, :id, :name, { :prompt => 'Select a product'},{ :multiple => true } %>
Is there a way to do this with select dropdown boxes instead?
Use nested forms for products:
<%= fields_for @company.products do |product_fields| %> <%= product_fields.collection_select :product_id, Product.all, :id, :name, { :prompt => 'Select a product' } %> <% end %>
精彩评论