Using rails 4、如何在父窗体中深度嵌套资源
Using rails 4, how to deeply nest resources in a parent form
正在编写食谱应用程序。很难把它写下来。
我的模特:
食谱
- has_many :recipe_ingredients
- has_many:成分,通过::recipe_ingredients
Recipe_Ingredient
- belongs_to:食谱
- belongs_to:成分
成分
- has_many :recipe_ingredients, :dependent => :destroy
- has_many:食谱,通过::recipe_ingredients
我的路线很简单
resources :recipes // 和其他一些随机的
在我的食谱控制器中:
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 个晚上。
特定错误似乎来自引用 @recipe.recipe_ingredient
(单数),它应该是复数形式,因为它是 has_many
关系。在您的 RecipeController#new
:
中试试这个
recipe_ingredients = @recipe.recipe_ingredients.build
然后,对于 recipe_ingredients.ingredient
,请尝试使用 build_association
:
recipe_ingredients.build_ingredient
正在编写食谱应用程序。很难把它写下来。
我的模特:
食谱
- has_many :recipe_ingredients
- has_many:成分,通过::recipe_ingredients
Recipe_Ingredient
- belongs_to:食谱
- belongs_to:成分
成分
- has_many :recipe_ingredients, :dependent => :destroy
- has_many:食谱,通过::recipe_ingredients
我的路线很简单
resources :recipes // 和其他一些随机的
在我的食谱控制器中:
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 个晚上。
特定错误似乎来自引用 @recipe.recipe_ingredient
(单数),它应该是复数形式,因为它是 has_many
关系。在您的 RecipeController#new
:
recipe_ingredients = @recipe.recipe_ingredients.build
然后,对于 recipe_ingredients.ingredient
,请尝试使用 build_association
:
recipe_ingredients.build_ingredient