8

I have a Recipe model, which has Ingredients embedded in it, using 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

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:

_form.html.erb - Used in Recipe views

<%= 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 Controller

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

Ingredients Controller

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

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?

purpletonic
  • 1,858
  • 2
  • 18
  • 29
  • If I'm missing any information needed to solve this, then please let me know, because I'm still stumped on this one... – purpletonic Jul 17 '11 at 16:15

2 Answers2

9

When you show the nested form, try using (notice the equals):

<%= f.fields_for

Instead of just

<% f.fields_for

See this similar question.

Community
  • 1
  • 1
ericvg
  • 3,907
  • 1
  • 30
  • 35
2

I had a very similar issue recently. I found this similar question posted on the Mongoid issue tracker on Github to be very helpful:

https://github.com/mongoid/mongoid/issues/1468#issuecomment-6898898

The skinny is that the line

= f.fields_for :ingredients do |builder|

should look like this:

= f.fields_for @recipe.ingredients do |builder|
user456584
  • 86,427
  • 15
  • 75
  • 107