has_many:通过可以构建多个实例的nested_form

时间:2011-04-21 15:09:01

标签: jquery ruby-on-rails ruby-on-rails-3 many-to-many nested-forms

我的模型中有以下代码:

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

我有一个表单来创建一个新的Farm,我想和这个表单一起创建farm_products。我的farm_products表不仅包含外键字段。如何通过Javascript和/或JQuery添加或删除嵌套列?

UPD。我通过nested_forms找到了一个很棒的宝石,它正是我想做的! 这是我视图中的代码

= 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

但是出现了错误

undefined method `klass' for nil:NilClass

我的关系可能有问题,但我找不到问题。

1 个答案:

答案 0 :(得分:7)

link_to_add需要在fields_for块之外,在f对象上调用,不在fp对象上。