茧嵌套属性为空 link_to_add_association

Empty link_to_add_association for cocoon nested attributes

我将 simple_form 与 cocoon (https://github.com/nathanvda/cocoon) 一起使用,一切正常。

我唯一真正不喜欢的是我必须初始化空实例才能使其工作:

def new
  @facility = Facility.friendly.find(params[:facility_slug])
  @pet = @facility.pets.build(animal: Dog.new)
  @pet.pet_pictures.build
  @pet.animal.mixtures.build
end

最后两行用于制作茧和 link_to_add_association 工作,如果我删除它们 link_to_add_association 完全是空的。

有谁知道如何使它更加地道并避免显式调用构建方法?我该如何改进此代码?

How can I improve this code?

通过将代码放入模型中:

#app/models/facility.rb
class Facility < ActiveRecord::Base
   def construct_pet animal
      model = animal.to_s.constantize
      pet = pets.build animal: model.send(:new)
      pet.pet_pictures.build
      pet.animal_mixtures.build
      pet
   end
end

#app/controllers/facilities_controller.rb
class FacilitiesController < ApplicationController
   def new
      @facility = Facility.find(params[:facility_slug]).construct_pet(:dog)
   end
end

您的问题不在于 cocoon,而是 Rails。

让我解释一下:


fields_for

你必须记住,rails 是 面向对象的,在这个术语的每一个意义上。

这意味着如果你想创建依赖数据(IE嵌套字段),你将不得不构建相关的关联模型实例。

没有办法解决这个问题;如果您不构建模型,Rails 将根本不知道如何构建 fields_for 方法。

当您创建关联模型时(IE 通过 accepts_nested_attributes_for 传递数据),Rails 必须有相关模型的实例才能传递。

如果不构建依赖模型,则得不到任何相关字段,因此无法正常工作。

Cocoon uses fields_for 的方式与 "manually" 完全相同:

从这里可以看出RailsCast and this answer I literally just wrote

--

avoid explicitly call the build method

不可能了,我的朋友。

build 方法创建实例关联模型的实例。如果您不希望它们显示(这是 fields_for 工作所必需的),您将无法使用它们。