Ruby on rails Rails,接受\u嵌套的\u属性\u for has\u many:through with build

Ruby on rails Rails,接受\u嵌套的\u属性\u for has\u many:through with build,ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 3,Ruby On Rails 4,我知道这里有很多类似的问题,但都没有帮到我 我有3种型号: class Product < ActiveRecord::Base has_many :product_option_types has_many :option_types, through: :product_option_types end class OptionType < ActiveRecord::Base has_many :product_option_types has_m

我知道这里有很多类似的问题,但都没有帮到我

我有3种型号:

class Product < ActiveRecord::Base
   has_many :product_option_types
   has_many :option_types, through: :product_option_types
end

class OptionType < ActiveRecord::Base
    has_many :product_option_types
    has_many :products, through: :product_option_types
end

class ProductOptionType < ActiveRecord::Base
    belongs_to :product
    belongs_to :option_type
end
在呈现new.html.erb之前,我需要按照以下方式构建产品选项类型

在视图new.html.erb中,我使用集合选择显示选项类型:

<%= 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 %>

然后要传递信息位置:1要创建操作,我必须使用表单中的隐藏字段?

据我所知,您感兴趣的数据是OptionType。 那么,为什么不处理数据而不是关系呢

 Product.first.option_types
比关系表更有趣


从产品选项类型更改为选项类型

对于你的第一个问题:好吧,它有效吗?如果没有,会发生什么?对于你的第二个问题,是的,你需要隐藏的_字段来传递位置-或者如果它无论如何都不会被修改,你可以简单地在你的create操作中设置,而不是在new中。这真的是一个大问题吗?
<%= 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 %>
@product.product_option_types.build(position: 1)
 Product.first.option_types