gpt4 book ai didi

ruby-on-rails - Rails has_many:through和collection_select具有多个

转载 作者:行者123 更新时间:2023-12-03 12:32:46 24 4
gpt4 key购买 nike

我有一个以下问题,使用has_many:通过collection_select:multiple => true在多选中通过多对多关系。我有一些供应商,他们可以交付许多可以由许多供应商交付的成分。看一看:

成分模型:

class Ingredient < ActiveRecord::Base
has_many :ingredient_suppliers
accepts_nested_attributes_for :ingredient_suppliers, :allow_destroy => true

has_many :suppliers, :through => :ingredient_suppliers
end


供应商模型:

class Supplier < ActiveRecord::Base
has_many :ingredient_suppliers
has_many :ingredients, :through => :ingredient_suppliers
end


关系实体:

class IngredientSupplier < ActiveRecord::Base
belongs_to :ingredient
belongs_to :supplier
end


这就是表格。请注意,如果不指定:name,则无法使它工作:

<%= form_for(@ingredient) do |f| %>
<%= f.fields_for :suppliers do |supplier_fields| %>
<%= supplier_fields.collection_select (:supplier_ids,
Supplier.all(:order=>"name ASC"),
:id, :name,
{:selected => @ingredient.supplier_ids,
:include_blank => true},
{:multiple => true,
:name => 'ingredient[supplier_ids]'}) %>
<% end %>
<% end %>


如果删除:name,则会收到此错误消息:

Supplier(#-617951108) expected, got Array(#-608411888)

Request

Parameters:

{"commit"=>"Anlegen",
"authenticity_token"=>"MuEYtngwThharmM1KaAbH8JD3bScXiDwj0ALMytxl7U=",
"_method"=>"put",
"utf8"=>"✓",
"id"=>"1",
"ingredient"=>{"name"=>"Ingredient 1",
"nr"=>"00100",
"unit"=>"kg",
"mol_per_unit"=>"2000,
00000",
"description"=>"",
"suppliers"=>{"supplier_ids"=>["1",
"2"]}}}


现在的问题是,PUT参数仅包含一个vendor_id,而不是一个vendor_id数组:

"ingredient"=>{"name"=>"Rohstoff 3", "nr"=>"00300", "unit"=>"Stk.", "mol_per_unit"=>"0,00000", "description"=>"", "supplier_ids"=>"2"}

最佳答案

我已经解决了问题。在这种情况下,使用fields_for是错误。解决方案是使用collection_select,如下所示:

<%= collection_select(:ingredient, :supplier_ids, 
Supplier.all(:order=>"name ASC"),
:id, :name, {:selected => @ingredient.supplier_ids, :include_blank => true}, {:multiple => true}) %>

关于ruby-on-rails - Rails has_many:through和collection_select具有多个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8239961/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com