我嵌套了試圖爲每個複選框插入Categorization
模型的表單。因此,我沒有收到任何錯誤,但Categorization
模型的其中一個屬性未插入到表中。這是哈希的樣子與2開出3複選框選中:"categorizations_attributes"=>{"0"=>{"clothing_size_id"=>["1", "2", ""]}}}
嵌套表單中的collection_check_boxes將不會正確插入到連接表中,多對多
插入如下: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")
如何正確插入?
使用Product
表單上的複選框顯示ClothingSize
型號的服裝尺寸。每個複選框應該在Categorization
模型中生成1行,並且每個複選框的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產品
<%= 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 %>
如果將'clothing_size_id'的所有實例更改爲複數,'clothing_size_ids',會發生什麼情況? –
嘿喬。當我在視圖中使其成爲複數時,我會爲#獲取'undefined method'clothing_size_ids'。當我在'def product_params方法'的'Products'控制器中使其成爲複數時,我得到'unpermitted parameters:clothing_size_id ' –
gjarnos