【发布时间】:2011-08-10 09:37:18
【问题描述】:
我的模型中有以下代码:
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_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
我的人际关系可能有问题,但我找不到问题。
【问题讨论】:
-
accepts_nested_attributes_for通常用于has_many关联,而不是多态关联。 -
farm_products 是否特定于农场?我的意思是,farm_products 会是通用的,例如不同农场想要共享它们的标签吗?
-
farm_products 包含farm_id、product_id、价格。产品表是产品的一种静态集合。所有农场都有相同的产品,但价格不同。
标签: jquery ruby-on-rails ruby-on-rails-3 many-to-many nested-forms