8

Tengo un modelo de receta, que tiene ingredientes incrustados en él, usando Mongoid.¿Cómo creo un formulario anidado utilizando los recursos incrustados de Mongoid en 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 

Quiero ser capaz de crear una nueva receta y los ingredientes asociados para esa receta, al mismo tiempo, pero estoy luchando para entender cómo me gustaría ir sobre hacer esto. Esto es lo que tengo hasta ahora:

_form.html.erb - Se utiliza en receta Visitas

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

controlador Receta

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 

Ingredientes Controlador

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 

Esto hace que los nuevos ingredientes se formen, pero no hay campos para los ingredientes. ¿Alguien puede darme algunos consejos sobre lo que estoy haciendo mal?

+0

Si me falta la información necesaria para resolver esto, hágamelo saber, porque todavía estoy perplejo con esta ... – purpletonic

Respuesta

8

Al mostrar la forma anidada, trate de usar (note los iguales):

<%= f.fields_for 

En lugar de simplemente

<% f.fields_for 

Ver este question similares.

2

Tuve un problema muy similar recientemente. He encontrado esta pregunta similar publicado en el seguimiento de incidencias Mongoid en Github a ser muy útil:

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

El flaco es que la línea

= f.fields_for :ingredients do |builder| 

debería tener este aspecto:

= f.fields_for @recipe.ingredients do |builder| 
+0

Esto no funcionó para mí como del 1/25/2013. –

+0

Quizás tuviste un problema diferente? – user456584

Cuestiones relacionadas