Srdjan Cengic
2013-Dec-20 12:39 UTC
Rails, accepts_nested_attributes_for has_many: through with build
I have 3 models: class Product < ActiveRecord::Base has_many :product_option_types has_many :option_types, through: :product_option_typesend class OptionType < ActiveRecord::Base has_many :product_option_types has_many :products, through: :product_option_typesend class ProductOptionType < ActiveRecord::Base belongs_to :product belongs_to :option_typeend Table OptionType is predefined with following: [image: enter image description here] Now when creating new Product i need to populate also table product_option_types with product_id and option_type id: Here is the design of product_option_types table: [image: enter image description here] Far as i know i need accepts_nested_attributes_for in Product model to refference product_option_types, so in product model i need following *?* accepts_nested_attributes_for :product_option_types, allow_destroy: true Before rendering new.html.erb then i need to build product_option_types on the following way *?* @product = Product.new-vsVTqSbophf5vxNyLA01Fg@public.gmane.org_option_types.build(position: 1) In the view new.html.erb i'm using collection_select to display option_types: <%= f.fields_for :product_option_types do |builder| %> <%= builder.label :option_type_id, "Options" %> <%= builder.collection_select :option_type_id, OptionType.all(order: 'name ASC'), :id, :name, { prompt: "Select option..."} %><% end %> Finally in the crate action of product controller i must permit also association attributes like: permited = params[:product].permit(product_option_types_attributes: [:option_type_id]) *So main question is, did i set up accepts_nested_attributes_for, build, collection_select and associations correctly?* +: When im building associoation with parameters like: @product.product_option_types.build(position: 1) *Then to pass that information(position: 1) to create action i must use hidden_field in form?* -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/211d7da9-1817-429b-86f1-74db1d952535%40googlegroups.com. For more options, visit https://groups.google.com/groups/opt_out.