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
CustomPropertyTranslation
和OptionTranslation
的嵌套表单。
= 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
我不想自动构建多个CustomPropertyTranslation
和OptionTranslation
,具体取决于该地区的语言数量。
我尝试使用after_initialize
回调来构建必要的关联,但它仅适用于现有的自定义属性。如何在点击add translation
上一次构建多个关联?
答案 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