ruby on rails - How to build several objects while adding association? -


rails 4.2.1, ruby 2.2.1 relations are:

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 

in region form i'm using cocoon nested fields.

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

and nested form custompropertytranslation , optiontranslation.

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

i wan't automatically build several custompropertytranslation , optiontranslation depending on how many languages region has.

i tried use after_initialize callback build necessary associations worked existing custom properties. how build several associations @ once on click add translation ?

you can use count key in html_options of link_to_add_association helper determine how many new objects want create

= f.simple_fields_for :custom_property_translations |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} 

more on available options here: https://github.com/nathanvda/cocoon/blob/be59abd99027b0cce25dc4246c86d60b51c5e6f2/lib/cocoon/view_helpers.rb


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -