我有嵌套的表单,试图插入每个复选框的分类模型.结果,我没有得到错误,但分类模型的一个属性没有插入到表中.这是散列的样子,选中了3个复选框中的2个:“categorizations_attributes”= {“
插入内容如下所示:SQL(0.4ms)INSERT INTO“Categorizations”(“created_at”,“product_id”,“updated_at”)VALUES($1,$2,$3)返回“id”[[“created_at”,Mon,23 2014年6月17:44:45 UTC 00:00],[“product_id”,15],[“updated_at”,星期一,2014年6月23日17:44:45 UTC 00:00]]
插件需要使用“clothes_size_id”来构建,我认为这样(“created_at”,“product_id”,“updated_at”,“clothing_size_id”)
如何正确插入?
正在使用“产品”表单上的复选框显示ClothingSize模型中的服装尺寸.每个复选框应该在Categorization模型中使用相同的product_id和每个复选框的clothing_size_id进行1行检查.
楷模
产品
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 %>我想你想要从分类中取出你的衣服尺寸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
结束
尝试一下,让我知道它是否有效.