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 = [email protected]_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?