has_many :通过nested_form可以构建多个实例 [英] has_many :through nested_form that can build multiple instances

查看:13
本文介绍了has_many :通过nested_form可以构建多个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型中有以下代码:

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?

更新.我通过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 上调用code> 对象不在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆