4

I have the following code in my models:

Class Farm < ActiveRecord::Base
  has_many :farm_products, :dependent => :destroy
  has_many :products, :through => :farm_products
  accepts_nested_attributes_for :farm_products
end

class Product < ActiveRecord::Base
  has_many :farm_products, :dependent => :destroy
  has_many :farms, :through => :farm_products
end

class FarmProduct < ActiveRecord::Base
  belongs_to :farm
  belongs_to :product
end

I have a form to create a new Farm, and I want to create farm_products along with this form. My farm_products table can not only contain foreign key fields. How can I add or remove nested columns via Javascript and/or JQuery?

UPD. I found an awesome gem by nested_forms that doing exactly what I want! Here is a code in my view

= nested_form_for @farm, :html => { :multipart => true } do |f|
  = f.fields_for :farm_products do |fp|
-#fields goes here
     = fp.link_to_remove 'Remove this task'
     = fp.link_to_add "Add a task", :farm_products

But got an error that says

undefined method `klass' for nil:NilClass

There is probably something wrong with my relationships, but i can't find the problem.

Petya petrov
  • 2,153
  • 5
  • 23
  • 35
  • `accepts_nested_attributes_for` is usually used for a `has_many` association, not a polymorphic association. – thenengah Apr 21 '11 at 15:31
  • Will farm_products be specific to farms? What I mean is will farm_products be generic such as tags where different farms will want to share them? – thenengah Apr 21 '11 at 15:32
  • farm_products contains farm_id, product_id, price. And products table is a sort of static collection of products. All farms have the same products, but price is different. – Petya petrov Apr 21 '11 at 15:44

1 Answers1

7

The link_to_add needs to be outside the fields_for block, called on the f object not on the fp object.

smathy
  • 26,283
  • 5
  • 48
  • 68