0

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 %> 
mvanio
  • 505
  • 3
  • 15
  • The answer located here: http://stackoverflow.com/questions/2182428/rails-nested-form-with-has-many-through-how-to-edit-attributes-of-join-model?rq=1 – mvanio May 19 '15 at 15:20
  • The answer is the same as found [here](http://stackoverflow.com/questions/2182428/rails-nested-form-with-has-many-through-how-to-edit-attributes-of-join-model?rq=1) – mvanio Oct 05 '15 at 17:52

1 Answers1

0

The answer is the same as found here

The build method signature is different for has_one and has_many associations.

class User < ActiveRecord::Base
  has_one :profile
  has_many :messages
end

The build syntax for has_many association:

user.messages.build

The build syntax for has_one association:

user.build_profile  # this will work

user.profile.build  # this will throw error

Read the has_one association documentation for more details.

Community
  • 1
  • 1
mvanio
  • 505
  • 3
  • 15