Ruby on rails 如何使用Rails 3中的Mongoid嵌入式资源创建嵌套表单?
我有一个配方模型,使用Mongoid将配料嵌入其中Ruby on rails 如何使用Rails 3中的Mongoid嵌入式资源创建嵌套表单?,ruby-on-rails,ruby-on-rails-3,mongodb,mongoid,ruby-on-rails-3.1,Ruby On Rails,Ruby On Rails 3,Mongodb,Mongoid,Ruby On Rails 3.1,我有一个配方模型,使用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].bla
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-用于配方视图
<%= 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 %>
配料控制器
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
这将呈现新的配料表单,但没有用于配料的字段。有人能告诉我我做错了什么吗?当显示嵌套表单时,请尝试使用(注意等式):
我最近遇到了一个非常类似的问题。我发现Github上Mongoid问题跟踪器上发布的类似问题非常有用:
那条线是瘦的吗
= f.fields_for :ingredients do |builder|
应该是这样的:
= f.fields_for @recipe.ingredients do |builder|
如果我遗漏了解决这个问题所需的任何信息,那么请让我知道,因为我仍然在这个问题上感到困惑…也许你有不同的问题?
<% f.fields_for
= f.fields_for :ingredients do |builder|
= f.fields_for @recipe.ingredients do |builder|