9

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?

1
  • If I'm missing any information needed to solve this, then please let me know, because I'm still stumped on this one... Commented Jul 17, 2011 at 16:15

2 Answers 2

10

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

<%= f.fields_for

Instead of just

<% f.fields_for

See this similar question.

Sign up to request clarification or add additional context in comments.

Comments

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|

1 Comment

Maybe you had a different issue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.