8

我有一個食譜模型,其中嵌入了成分,使用Mongoid。如何在Rails 3中使用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 

我希望能夠創建一個新的配方,以及該配方中的成分有關,在同一時間,但我在努力明白,我怎麼會去這樣做。這是我迄今:

_form.html.erb - 使用配方視圖

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

規則控制器

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 

配料控制器

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 

這呈現新的成分形式,但沒有成分領域。任何人都可以給我任何指針,我做錯了什麼?

+0

如果我錯過了解決這個問題所需的任何信息,請讓我知道,因爲我仍然難住這一個... – purpletonic

回答

8

當你告訴嵌套形式,嘗試使用(注意等號):

<%= f.fields_for 

而不是僅僅

<% f.fields_for 

看到這個類似question

2

我最近有一個非常類似的問題。我發現張貼在Github上的Mongoid問題跟蹤這個類似的問題是非常有幫助的:

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

的骨感是該行

= f.fields_for :ingredients do |builder| 

應該是這樣的:

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

這不適合我2013年1月25日。 –

+0

也許你有一個不同的問題? – user456584