【问题标题】:has_many :through nested_form that can build multiple instanceshas_many :通过可以构建多个实例的nested_form
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多