我知道这里有一堆类似的问题,但都没有帮助我。Rails,accep_nested_attributes_for has_many:通过构建
我有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
表optionType为预定义了以下内容:
现在,创造新的产品时,我也需要填充的product_id和option_type ID表product_option_types:这里是product_option_types表的设计:
据我所知,我需要在产品模型中使用accept_nested_attributes_for来引用product_option_types,因此在产品模型中,我需要以下?
accepts_nested_attributes_for :product_option_types, allow_destroy: true
渲染new.html.erb然后我需要在下列方式建立product_option_types之前?
@product = Product.new
@product.product_option_types.build(position: 1)
在我使用collection_select显示option_types视图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 %>
最后,在产品控制器的板条箱动作我必须允许也关联属性,如:
permited = params[:product].permit(product_option_types_attributes: [:option_type_id])
所以主要问题是,我是否设置了accepted_nested_attributes_for,b uild,collection_select和关联是否正确?
+:当IM建筑associoation与像参数:
@product.product_option_types.build(position: 1)
然后传递该信息(位置:1)来创建动作我必须在形式使用hidden_field?
对于你的第一个问题:好吧,它工作吗?如果不是,会发生什么呢?对于第二个问题,是的,你需要'hidden_field'来传递位置 - 或者如果它不会被修改,你可以简单地在你的'create'动作而不是'new'中设置。 – janfoeh
这真的是个大问题吗? – Srle