I believe I've read all related answers on SO but still not found a solution, so here's my issue. I have 'inherited' an application that is to work with Products, Batches and Quantities. A Batch will have many Products, Products can appear in many Batches and in many Quantities. So a has_many :through relationship is implied because the join table will have an extra column for the product quantity;
class Batch < ActiveRecord::Base
has_many :quantities
has_many :products, :through => :quantities
accepts_nested_attributes_for :products
end
class Product < ActiveRecord::Base
has_many :quantities
has_many :batches, :through => :quantities
accepts_nested_attributes_for :quantities
end
class Quantity < ActiveRecord::Base
belongs_to :product
belongs_to :batch
end
Now, supposing I need to create a new Batch. I'd like the user to be able to specify the Product(s) to appear in the Batch, but also the Quantity of each product.
How do I setup my form so that both Product and Quantity can be specified? I may need some details for the controller and form too. In the 'new' action I can build the required models with;
@batch = Batch.new
@qty = @batch.quantities.build.build_product
But I'm then left floundering with the form - how should the fields be specified?
<%= form_for(@batch) do |f| %>
<% f.fields_for :products do |prod_form| %>
<% prod_form.fields_for :quantity do |qty_form| %>
<% end %>
<% end %>
<% end %>