has_many:通过nested_form可以构建多个实例 [英] has_many :through nested_form that can build multiple instances
问题描述
我的模型中包含以下代码:
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
我有一个用于创建新农场的表单,并且我希望与此表单一起创建farm_products.我的farm_products表不仅可以包含外键字段.如何通过Javascript和/或JQuery添加或删除嵌套列?
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.我通过nested_forms找到了一个很棒的宝石,它确实可以完成我想要的! 这是我认为的代码
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
但是出现错误消息
undefined method `klass' for nil:NilClass
我的人际关系可能出了点问题,但是我找不到问题.
There is probably something wrong with my relationships, but i can't find the problem.
推荐答案
link_to_add
必须在fields_for
块之外,在f
对象而不是fp
对象上调用.
The link_to_add
needs to be outside the fields_for
block, called on the f
object not on the fp
object.
这篇关于has_many:通过nested_form可以构建多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!