Tôi có một mô hình Công thức, trong đó có Thành phần được nhúng trong đó, sử dụng Mongoid.Làm cách nào để tạo biểu mẫu lồng nhau bằng tài nguyên được nhúng Mongoid trong Rails 3?
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
Tôi muốn có thể tạo công thức mới và các thành phần liên quan cho công thức đó, đồng thời, nhưng tôi đang cố gắng hiểu cách tôi làm việc này. Đây là những gì tôi có cho đến nay:
_form.html.erb - Được sử dụng trong Recipe xem
<%= 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 %>
Recipe khiển
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
Bộ điều khiển thành phần
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
Điều này làm cho mẫu thành phần mới, nhưng không có trường cho các thành phần. Bất cứ ai có thể cho tôi bất kỳ con trỏ như những gì tôi đang làm sai?
Nếu tôi thiếu bất kỳ thông tin nào cần thiết để giải quyết vấn đề này, vui lòng cho tôi biết, bởi vì tôi vẫn bị bối rối về điều này ... – purpletonic