【发布时间】:2016-02-03 14:39:31
【问题描述】:
我尝试做的是一个简单的 Plate 表格,您可以在其中选择您想要的成分。成分的数量和名称可能因天而异。
每次创建一个新盘子时,它都会创建 4 个新选项,其中包含 plate_id 和 ingredient_id 以及一个布尔值 chosen。 plate_id 来自新盘子创建,ingredient_id 应该是我数据库中现有成分的 ID,chosen 是该成分是否应该在盘子中。
这是我的课程板块、选择和成分:
class Plate < ActiveRecord::Base
has_many :choices
has_many :ingredients, through: :choices
accepts_nested_attributes_for :choices
end
class Choice < ActiveRecord::Base
belongs_to :plate
belongs_to :ingredient
accepts_nested_attributes_for :ingredient
end
class Ingredient < ActiveRecord::Base
has_many :choices
has_many :plates, through: :choices
end
我的 Plate 嵌套形式如下所示:
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<%= f.fields_for :choices do |fc| %>
<%= fc.check_box :chosen %>
<%= fc.fields_for :ingredient do |fi| %>
<%= fi.text_field(:name)%> <br />
<% end %>
<% end %>
最后是我的 Plate 控制器:
def new
@plate = Plate.new
@choice1 = @plate.choices.build
@choice2 = @plate.choices.build
@choice3 = @plate.choices.build
@choice4 = @plate.choices.build
@ingredient1 = Ingredient.find_by_name('peach')
@ingredient2 = Ingredient.find_by_name('banana')
@ingredient3 = Ingredient.find_by_name('pear')
@ingredient4 = Ingredient.find_by_name('apple')
@choice1.ingredient_id = @ingredient1.id
@choice2.ingredient_id = @ingredient2.id
@choice3.ingredient_id = @ingredient3.id
@choice4.ingredient_id = @ingredient4.id
end
def plate_params
params.require(:plate).permit(:name, choices_attributes: [:chosen, ingredient_attributes: [ :name]])
end
我的问题是,当我创建一个新盘子时,它会创建与所选盘子名称相同的新成分(但当然具有不同的 id),并且 Choices 具有创建的新成分的成分 ID。
我尝试在嵌套属性中添加:id:params.require(:plate).permit(:name, choices_attributes: [:chosen, ingredient_attributes: [:id, :name]])
但是当我这样做时,我会出错:
在 ID=1 的选择中找不到 ID=1 的成分
我搜索了答案,但找不到任何答案,我想我对 Rails 参数、表单和嵌套属性的了解不足以理解问题出在哪里。
感谢您的帮助!
ps:这是我关于 Stack Overflow 的第一个问题,如果我的问题有任何问题,请告诉我
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 nested-attributes