简体   繁体   English

Rails中的嵌套属性

[英]nested attribute in rails

I am trying to build a small recipe website. 我正在尝试建立一个小的食谱网站。 But when I try to use nested attribute for saving my child(recipe_ingredients) table through parent(recipe) action. 但是当我尝试使用嵌套属性通过parent(recipe)操作保存我的child(recipe_ingredients)表时。 It only generating ids for me without any data in it. 它只为我生成ID,而没有任何数据。 Could any one help? 有谁可以帮忙吗?

Model for recipe: 配方模型:

class Recipe < ActiveRecord::Base
  has_many :recipe_ingredients
  accepts_nested_attributes_for :recipe_ingredients, allow_destroy: true
end

Model for recipe_ingredients: 配方成分模型:

class RecipeIngredient < ActiveRecord::Base
  belongs_to :recipe, inverse_of: :recipe_ingredients
end

Controller for recipe: 配方控制器:

 def create
  @recipe = Recipe.new(recipe_params)
  @recipe.recipe_ingredients.build
  ***binding.pry***

 if @recipe.save
   render json: @recipe, status: :created, location: @recipe
 else
   render json: @recipe.errors, status: :unprocessable_entity
 end
end

 def recipe_params
   params.require(:recipes)
    .permit(:name, :category, instruction: [], recipe_ingredients_attributes: [:amount, :ingredient, :measure])
 end

``` ```

After I check with rails console, my recipe_params is like below 在我使用Rails控制台检查后,我的recipe_params如下所示

[7] pry(#<RecipesController>)> recipe_params Unpermitted parameter: recipe_ingredients => {"name"=>"an example recipe", "category"=>"fry", "instructions"=>["do it", "ignore it"]} I don't know how to solve that "Unpermitted parameter" problem. [7] pry(#<RecipesController>)> recipe_params Unpermitted parameter: recipe_ingredients => {"name"=>"an example recipe", "category"=>"fry", "instructions"=>["do it", "ignore it"]}我不知道如何解决“不允许的参数”问题。 Please help~ Thank you~ 请帮忙〜谢谢〜

尝试将您的recipe_params方法中的params.require(:recipes)更改为params.require(:recipe)希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM