加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 嵌套表单中的collection_check_boxes不会正确

发布时间:2020-12-17 01:33:39 所属栏目:百科 来源:网络整理
导读:我有嵌套的表单,试图插入每个复选框的分类模型.结果,我没有得到错误,但分类模型的一个属性没有插入到表中.这是散列的样子,选中了3个复选框中的2个:“categorizations_attributes”= {“0”= {“clothing_size_id”= [“1”,“2”,“”]}}} 插入内容如下所示
我有嵌套的表单,试图插入每个复选框的分类模型.结果,我没有得到错误,但分类模型的一个属性没有插入到表中.这是散列的样子,选中了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)返回“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”,“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,:sizes { prompt: "Size" } %>
  </div>
<% end %>

然后在你的控制器中:

def product_params
  params.require(:product).permit(:title,{ 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

结束

尝试一下,让我知道它是否有效.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读