如何在添加关联的同时构建多个对象?

How to build several objects while adding association?

Rails4.2.1,Ruby2.2.1 关系是:

class Region < ActiveRecord::Base
  has_many :translations,      dependent: :destroy  
  has_many :custom_properties, dependent: :destroy
  has_many :languages,         through: :translations
  has_many :options,           through: :custom_properties
  accepts_nested_attributes_for :custom_properties, reject_if: :all_blank, allow_destroy: true
  accepts_nested_attributes_for :translations,      reject_if: :all_blank, allow_destroy: true
end

class CustomProperty < ActiveRecord::Base
  belongs_to :region
  has_many :options, dependent: :destroy
  has_many :custom_property_translations, dependent: :destroy
  accepts_nested_attributes_for :options, reject_if: :all_blank, allow_destroy: true
  accepts_nested_attributes_for :custom_property_translations, reject_if: :all_blank, allow_destroy: true
end

class CustomPropertyTranslation < ActiveRecord::Base
  belongs_to :custom_property
  belongs_to :language
end


class Option < ActiveRecord::Base
  belongs_to :custom_property
  has_many :option_translations, dependent: :destroy
  accepts_nested_attributes_for :option_translations, reject_if: :all_blank, allow_destroy: true
end

class OptionTranslation < ActiveRecord::Base
  belongs_to :option
  belongs_to :language
end

在区域表单中,我对嵌套字段使用 cocoon

  = f.simple_fields_for :custom_properties do |custom_property|
    = render 'custom_property_fields', f: custom_property
  .links
    = link_to_add_association 'add property', f, :custom_properties

以及 CustomPropertyTranslationOptionTranslation 的嵌套形式。

= f.simple_fields_for :custom_property_translations do |custom_property_translation|
      = render 'custom_property_translation_fields', f: custom_property_translation
  .links
    = link_to_add_association t('.add_translation'), f, :custom_property_translations

我不想自动构建多个 CustomPropertyTranslationOptionTranslation,具体取决于该地区有多少种语言。

我尝试使用 after_initialize 回调来建立必要的关联,但它仅适用于现有的自定义属性。如何在单击时同时建立多个关联 add translation

您可以使用 link_to_add_association 助手的 html_options 中的 count 键来确定要创建多少个新对象

= f.simple_fields_for :custom_property_translations do |custom_property_translation|
      = render 'custom_property_translation_fields', f: custom_property_translation
  .links
    = link_to_add_association t('.add_translation'), f, :custom_property_translations, {count: 3}

有关可用选项的更多信息:https://github.com/nathanvda/cocoon/blob/be59abd99027b0cce25dc4246c86d60b51c5e6f2/lib/cocoon/view_helpers.rb