8

レシピモデルには、モンゴイドを使って、その中に成分が埋め込まれています。Mongoidに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 

私は新しいレシピを作成できるようにしたい、そしてそのレシピの関連する成分、同時に、私は私がこれをやって行きたいかを理解するために苦労しています。これは私がこれまで持っているものです。

_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

これを解決するために必要な情報が不足している場合、私はまだこの1つに困っているので私に知らせてください... – purpletonic

答えて

8

、(等号を気づか)を使用してみてください。代わりにちょうど

<% f.fields_for 

<%= f.fields_for 

をこの同様のquestionを参照してください。

2

私は最近非常に似た問題を抱えていました。

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

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

スキニーはライン

= f.fields_for :ingredients do |builder| 

は次のようになりますということです。私は非常に有用であることをGithubの上Mongoidの課題追跡に掲載これと同様の問題を発見しました

+0

これは私のためにはうまくいかなかった2013年1月25日の –

+0

別の問題があったのでしょうか? – user456584

関連する問題