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

时间:2015-09-21 07:04:23

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

Rails 4.2.1,Ruby 2.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上一次构建多个关联?

1 个答案:

答案 0 :(得分:0)

您可以使用count帮助html_options中的link_to_add_association键来确定要创建的新对象数量

= 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