我有嵌套的表单,试图为每个复选框插入Categorization
模型。因此,我没有收到任何错误,但Categorization
模型的某个属性未插入表中。这是哈希的样子,选中了3个复选框中的2个:"categorizations_attributes"=>{"0"=>{"clothing_size_id"=>["1", "2", ""]}}}
插入内容如下所示:SQL (0.4ms) INSERT INTO "categorizations" ("created_at", "product_id", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["created_at", Mon, 23 Jun 2014 17:44:45 UTC +00:00], ["product_id", 15], ["updated_at", Mon, 23 Jun 2014 17:44:45 UTC +00:00]]
插件需要使用"clothing_size_id"
来构建,我认为("created_at", "product_id", "updated_at", "clothing_size_id")
如何正确插入?
ClothingSize
表单上的复选框显示Product
模型中的服装尺寸。每个复选框都应在Categorization
模型中生成一行,并且选中product_id
并选中每个复选框的clothing_size_id
。
模型
产品
has_many :categorizations, dependent: :destroy
has_many :clothing_sizes, through: :categorizations
accepts_nested_attributes_for :categorizations
accepts_nested_attributes_for :clothing_sizes
分类
belongs_to :product
belongs_to :clothing_size
accepts_nested_attributes_for :clothing_size
ClothingSize
has_many :categorizations
has_many :products, through: :categorizations
accepts_nested_attributes_for :categorizations
accepts_nested_attributes_for :products
产品控制器
def new
@product = Product.new
@product.categorizations.build
end
def product_params
params.require(:product).permit(:title, :description,
:image_url, :image_url2, :price, :quantity, :color,
:clothing_sizes_attributes => [:sizes, :clothing_size_id],
:categorizations_attributes => {:clothing_size_id => []})
end
_form for Products
<%= form_for(@product) do |f| %>
<%= f.fields_for :categorizations do |cat| %>
<div class="field">
<%= cat.collection_check_boxes :clothing_size_id, ClothingSize.all, :id, :sizes, {prompt: "Size"} %>
</div>
<% end %>
<%= f.submit 'Save Product'%>
<% end %>
答案 0 :(得分:7)
我认为你想要从分类中取出你的衣服尺寸ID。
<%= form_for(@product) do |f| %>
<div class="field">
<%= f.collection_check_boxes :clothing_size_ids, ClothingSize.all, :id, :sizes { prompt: "Size" } %>
</div>
<% end %>
然后在你的控制器中:
def product_params
params.require(:product).permit(:title, :description,
:image_url, :image_url2, :price, :quantity, :color,
{ clothing_size_ids: [] })
end
最后,我认为你不需要接受产品模型中任何关联的嵌套属性。
class Product < ActiveRecord::Base
has_many :categorizations, dependent: :destroy
has_many :clothing_sizes, through: :categorizations
# accepts_nested_attributes_for :categorizations
# accepts_nested_attributes_for :clothing_sizes
end
端
尝试一下,让我知道它是否有效。