2015-03-31 43 views
0

编写配方应用程序。有一段时间让这个下来。使用rails 4,如何深度嵌套父表单中的资源

我的模型:

配方

  • 的has_many:recipe_ingredients
  • 的has_many:配料,通过:recipe_ingredients

Recipe_Ingredient

  • belongs_to的:配方
  • belongs_to的:成分

成分

  • 的has_many:recipe_ingredients,:依赖=>:破坏
  • 的has_many:配方,通过::recipe_ingredients

我的路线是简单

资源://食谱和一些随机OTHERS

在我的食谱控制器:

def new 
    @recipe = Recipe.new 
    recipe_ingredients = @recipe.recipe_ingredient.build 
    recipe_ingredients.ingredient.build 
end 

我的食谱表:

<%= simple_form_for @recipe do |r| %> 

<%= r.input :title, label: 'Recipe Name:' %> 
<%= r.input :description, label: 'Recipe Description' %> 

<%= r.simple_fields_for :recipe_ingredients do |ri| %> 
    <%= ri.input :quantity, label: "Quantity" %> 
    <%= ri.simple_fields_for :ingredients do |i| %> 
     <%= i.input :name, label: "name" %> 
    <% end %> 
<% end %> 
<%= r.button :submit %> 
<% end %> 

不确定我做错了什么。错误是:

undefined method `recipe_ingredient' for #<Recipe:0x000001034d3650> 

有什么想法吗?花了2晚在这。

回答

0

该错误似乎来自@recipe.recipe_ingredient(单数),应该复数化,因为它是has_many的关系。在RecipeController#new试试这个:

recipe_ingredients = @recipe.recipe_ingredients.build 

然后,对于recipe_ingredients.ingredient,请尝试使用build_association代替:

recipe_ingredients.build_ingredient 
+0

我明白你的意思,我更新了它吐出:对于无未定义的方法'建设”: NilClass on .ingredient。如果我将成分复数化,那么我得到一个未定义的方法成分。 – 2015-03-31 15:43:29

+0

对于'belongs_to'关联,请尝试使用'build_association'而不是'build'。我编辑了我的答案以反映这一点。 – Drenmi 2015-03-31 16:10:32

+1

感谢@Drenmi的笔记。这确实奏效。正确的行是:recipe_ingredients.build_ingredient – 2015-03-31 16:31:16