Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a nested form using Mongoid embedded resources in Rails 3?

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?

like image 400
purpletonic Avatar asked Jul 13 '11 21:07

purpletonic


2 Answers

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

<%= f.fields_for

Instead of just

<% f.fields_for

See this similar question.

like image 68
ericvg Avatar answered Oct 24 '22 11:10

ericvg


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|
like image 32
user456584 Avatar answered Oct 24 '22 09:10

user456584