我有一个Recipe模型,其中嵌入了成分,使用Mongoid。
class Recipe
include Mongoid::Document
include Mongoid::Timestamps
field :title, :type => String
embeds_many :ingredients
accepts_nested_attributes_for :ingredients, :reject_if => lambda { |a| a[:title].blank? }, :allow_destroy => true
validates :title, :presence => true
end
class Ingredient
include Mongoid::Document
field :name, :type => String
field :quantity, :type => String
embedded_in :recipe, :inverse_of => :ingredients
end
我希望能够同时创建一个新食谱,以及该食谱的相关成分,但我很难理解我该如何做到这一点。这是我目前所看到的:
_form.html。erb -用于Recipe视图
<%= form_for @recipe do |f| %>
...
<li>Title: <%= f.text_field :title %></li>
<% f.fields_for :ingredients do |builder| %>
<%= render "ingredient_fields", :f => builder %>
<% end %>
...
<%= f.submit %>
_ingredient_fields.html.erb
<%= f.text_field :name %>
配方控制器
def new
@recipe = Recipe.new
@ingredient = @recipe.ingredients.build
end
def create
@recipe = Recipe.new(params[:recipe])
if @recipe.save
redirect_to @recipe, notice: 'Recipe was successfully created.'
else
render action: "new"
end
end
配料控制器
def new
@recipe = Recipe.find(params[:recipe_id])
@ingredient = @recipe.ingredients.build
end
def create
@recipe = Recipe.find(params[:recipe_id])
@ingredient = @recipe.ingredients.build(params[:ingredient])
# if @recipe.save
end
这将呈现新的成分表单,但是没有成分字段。谁能告诉我我哪里做错了吗?
显示嵌套表单时,尝试使用(注意等号):
<%= f.fields_for
而不是
<% f.fields_for
参见这个类似的问题
我最近遇到了一个非常类似的问题。我发现这个类似的问题张贴在Github上的蒙古问题跟踪器非常有帮助:
https://github.com/mongoid/mongoid/issues/1468 issuecomment - 6898898
这一行
= f.fields_for :ingredients do |builder|
应该像这样:
= f.fields_for @recipe.ingredients do |builder|