Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I create a nested form using Mongoid embedded resources in Rails 3?
    primarykey
    data
    text
    <p>I have a Recipe model, which has Ingredients embedded in it, using Mongoid. </p> <pre><code>class Recipe include Mongoid::Document include Mongoid::Timestamps field :title, :type =&gt; String embeds_many :ingredients accepts_nested_attributes_for :ingredients, :reject_if =&gt; lambda { |a| a[:title].blank? }, :allow_destroy =&gt; true validates :title, :presence =&gt; true end class Ingredient include Mongoid::Document field :name, :type =&gt; String field :quantity, :type =&gt; String embedded_in :recipe, :inverse_of =&gt; :ingredients end </code></pre> <p>I want to be able to create a new recipe, and the associated ingredients for that recipe, at the same time, but I'm struggling to understand how I'd go about doing this. This is what I have thus far:</p> <p>_form.html.erb - Used in Recipe views</p> <pre><code>&lt;%= form_for @recipe do |f| %&gt; ... &lt;li&gt;Title: &lt;%= f.text_field :title %&gt;&lt;/li&gt; &lt;% f.fields_for :ingredients do |builder| %&gt; &lt;%= render "ingredient_fields", :f =&gt; builder %&gt; &lt;% end %&gt; ... &lt;%= f.submit %&gt; </code></pre> <p>_ingredient_fields.html.erb</p> <pre><code>&lt;%= f.text_field :name %&gt; </code></pre> <p>Recipe Controller</p> <pre><code>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 </code></pre> <p>Ingredients Controller</p> <pre><code>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 </code></pre> <p>This renders the new ingredients form, but there are no fields for the ingredients. Can anyone give me any pointers as to what I'm doing wrong?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload