我有一个名为@miniset
它通过@scale
模型接受@size
的嵌套属性,其格式为new.html.erb。
直到最近它才开始提交嵌套信息TWICE。
它会为其创建@miniset
和@size
,但之后会创建另一个@size
,其中包含相同的信息,但却缺少:scale_id
。
我环顾四周,完全不知道为什么要开始这样做。
我真的不知道要包含哪些代码。
这是日志:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"FpDJeyhp8Qb17v6H6EF+ZXi0562cyNv6oV+yl/HrT8I=", "miniset"=>{"name"=>"Test please work", "quantity"=>"4", "material"=>"Hard Plastic", "sizes_attributes"=>{"0"=>{"scale_id"=>"1"}}, "pcode"=>"", "release_date(1i)"=>"", "release_date(2i)"=>"", "release_date(3i)"=>"", "notes"=>""}, "Set Scale"=>{"#<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Size:0x007ff9a9cd8728>"=>""}, "commit"=>"Add set"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'd59f28d384d62b71719dd845b4e5353cdd993016' LIMIT 1
(0.3ms) begin transaction
SQL (5.6ms) INSERT INTO "minisets" ("created_at", "material", "name", "notes", "pcode", "quantity", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["created_at", Mon, 27 Jan 2014 20:10:49 UTC +00:00], ["material", "Hard Plastic"], ["name", "Test Please Work"], ["notes", ""], ["pcode", ""], ["quantity", 4], ["updated_at", Mon, 27 Jan 2014 20:10:49 UTC +00:00]]
SQL (0.8ms) INSERT INTO "sizes" ("created_at", "miniset_id", "scale_id", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Mon, 27 Jan 2014 20:10:49 UTC +00:00], ["miniset_id", 8], ["scale_id", 1], ["updated_at", Mon, 27 Jan 2014 20:10:49 UTC +00:00]]
SQL (0.4ms) INSERT INTO "sizes" ("created_at", "miniset_id", "updated_at") VALUES (?, ?, ?) [["created_at", Mon, 27 Jan 2014 20:10:49 UTC +00:00], ["miniset_id", 8], ["updated_at", Mon, 27 Jan 2014 20:10:49 UTC +00:00]]
这是处理尺寸/比例的形式:
<%= f.fields_for :sizes do |size_fields| %>
<%= size_fields.label :scale_id, simple_pluralize(@miniset.scales.count, 'Scale') %>
<%= hidden_field "Set Scale", @miniset.sizes %>
<div class = "form-inline"><%= size_fields.select :scale_id, options_from_collection_for_select(Scale.all, :id, :name, {:selected => @miniset.scales.map(&:id)}) %>
<% end %></div>
在我的mindsets_controller中我有
def create
@miniset = Miniset.new(miniset_params)
@size = @miniset.sizes.build
if @miniset.save
redirect_to @miniset
else
render 'new'
end
以下我有mini set_params
def miniset_params
params.require(:miniset).permit(:name, :release_date, :material, :pcode, :notes, :quantity, sizes_attributes: [:id, :scale_id, :miniset_id])
end
如果您认为可以帮助隔离问题但需要其他代码,请告诉我,我会对此进行编辑。 ERK。
答案 0 :(得分:4)
问题是你在表单中设置sizes_attributes然后在保存之前在Controller中构建另一个Size
子节点。
您会注意到保存的第二个尺寸缺少“scale_id”,因此尺寸与表格中的尺寸不同。
def create
@miniset = Miniset.new(miniset_params) # Miniset AND Size initialized from params
@size = @miniset.sizes.build # ANOTHER Size initialized, remove this line
if @miniset.save
redirect_to @miniset
else
render 'new'
end
end
问题是:@size = @miniset.sizes.build
在您通过nested_attributes创建子项时没有必要。