has_many :through nested_form that can build multiple instances

家住魔仙堡 提交于 2019-11-26 21:26:12

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/5746006/has-many-through-nested-form-that-can-build-multiple-instances

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!