2015-09-21 55 views
0

的Rails 4.2.1,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 

我wan't自动建立几个CustomPropertyTranslationOptionTranslation取决于许多语言是如何的区域了。

我试图使用after_initialize回调来建立必要的关联,但它只适用于现有的自定义属性。如何在点击add translation时一次建立多个关联?

回答

0

可以使用counthtml_optionslink_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

+0

确定。我能以某种方式提供价值吗? 如果我创建等于'region.languages'大小的翻译,则没有理由不锁定选择标记。 –

+0

你可以提供你想要count的值,它会渲染指定的对象,我不能完全明白你的意思,“没有理由锁定选择标记”? – bigsolom

+0

假设我们在该地区有3种语言。当我点击“添加翻译”链接时,我看到3对输入(语言和翻译文本字段的选择标签)添加(因为“{count:@ region.languages.size}”)。我是否也可以提供值来选择标签?因为每个翻译总是会有1种语言 –

相关问题