2015-09-21 56 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種語言 –

相關問題