【问题标题】:Empty link_to_add_association for cocoon nested attributes茧嵌套属性的空 link_to_add_association
【发布时间】:2015-10-07 09:22:15
【问题描述】:

我将 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

最后两行是为了让 cocoon 和 link_to_add_association 工作,如果我删除它们,link_to_add_association 是完全空的。

有谁知道如何使它更符合习惯并避免显式调用 build 方法?如何改进此代码?

【问题讨论】:

  • link_to_add_association 为空是什么意思?我用过 Cocoon 并且从来不需要构建项目来让它工作。带有关联的模型代码和视图代码中有什么?
  • 实际上很奇怪,我同意:基本上它不输出任何东西。您可以确认您是从头开始创建记录,而不是向已经存在的内容添加关联?

标签: ruby-on-rails ruby refactoring cocoon-gem


【解决方案1】:

如何改进此代码?

通过将代码放入模型中:

#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 的方式与“手动”操作完全相同:

你可以从这个RailsCastthis answer I literally just wrote看到。

--

避免显式调用构建方法

尽量不要,我的朋友。

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

【讨论】:

    猜你喜欢
    • 2017-08-22
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    相关资源
    最近更新 更多