简体   繁体   English

通过Rails中的关联使用has_many创建新模型时出现不允许的参数错误

[英]Unpermitted parameter error in creating new model with has_many through association in Rails

I'm writing an Recipe app in Rails. 我正在用Rails编写Recipe应用程序。 Now I'm stuck in this error. 现在,我陷入了这个错误。 I spent a week to find the solution for this problem. 我花了一个星期的时间找到解决该问题的方法。

Update model Here is my model: 更新模型这是我的模型:

class Recipe < ActiveRecord::Base
  has_many :ingredient_recipes
  has_many :ingredients, :through => :ingredient_recipes

  accepts_nested_attributes_for :ingredient_recipes
end

class Ingredient < ActiveRecord::Base
  has_many :ingredient_recipes
  has_many :recipes, :through => :ingredient_recipes
end

class IngredientRecipe < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :ingredient
end

IngredientRecipe is a join model that is used to store the value of recipe and ingredient. IngredientRecipe是一个联接模型,用于存储配方和配料的值。

In 'New' action, I want to create new recipe along with the Ingredient for that recipe, and specify the quantity (quantity is an additional attribute in the join table IngredientRecipe) for that ingredient. 在“新建”操作中,我要为该食谱创建新的食谱以及“配料”,并指定该配料的数量(数量是联接表“配料食谱”中的附加属性)。

When I click submit, it just creates a new Recipe, it doesn't create a record in the Join table. 当我单击“提交”时,它只是创建一个新配方,而没有在“联接”表中创建记录。

Here is my error: 这是我的错误:

Parameters: {"utf8"=>"✓", 
"authenticity_token"=>"AbnDeDLDWq3lvy4pozvXStVy7NeOIUuv1DU1U2/2EJ6n
 /jM6E1669hyB90733XTY9DGAvc2hbbDmbL6NwhqCUg==", 
"recipe"=>{"rec_name"=>"j", "rec_description"=>"k",
           "ingredient_recipe"=>{"ingredient"=>{"id"=>"1"},
           "quantity"=>"1"}}, "commit"=>"Create Recipe"}

Unpermitted parameter: ingredient_recipe 
(0.1ms)  BEGIN
  SQL (0.2ms)  INSERT INTO `recipes` (`rec_name`, `rec_description`, 
   `created_at`, `updated_at`) VALUES ('j', 'k', '2015-06-25 21:48:09', '2015-06-25 21:48:09')
 (1.1ms)  COMMIT  

Redirected to http://localhost:3000/recipes/50
Completed 302 Found in 6ms (ActiveRecord: 1.4ms)

Updated controller My recipe controller: Updated controller 更新的控制器我的配方控制器:更新的控制器

    def new
    @recipe = Recipe.new
    3.times { @recipe.ingredient_recipes.build.build_ingredient }
  end
    def create
        @recipe = Recipe.new(recipe_params)
        respond_to do |format|
          if @recipe.save
            format.html { redirect_to @recipe, notice: 'Recipe was successfully created.' }
            format.json { render :show, status: :created, location: @recipe }
          else
            format.html { render :new }
            format.json { render json: @recipe.errors, status: :unprocessable_entity }
          end
    end
  end

My recipe view form: 我的食谱视图表格:

    <%= form_for(@recipe) do |f| %>
  <% if @recipe.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@recipe.errors.count, "error") %> prohibited this recipe from being saved:</h2>
      <ul>
      <% @recipe.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :rec_name %><br>
    <%= f.text_field :rec_name %>
  </div>
  <div class="field">
    <%= f.label :rec_description %><br>
    <%= f.text_area :rec_description %>
  </div>
  <table>
    <thead>
      <tr>
        <th>Ingredients</th>
        <th>Unit</th>
        <th>Quantity</th>
        <th>New Quantity</th>
      </tr>
    </thead>
    <tbody>
      <%= f.fields_for :ingredient_recipes do |fi| %>
        <%= fi.fields_for do |i| %>
          <tr>
            <td> <%=i.collection_select(:ingredient_id, Ingredient.all, :id, :ing_name) %></td>
        <% end %>
            <td> <%=fi.text_field :quantity %></td>
          </tr>
      <% end %>
    </tbody>
  </table>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

No errors after I updated but here is the parameters what I get when I submit create action: Parameters: {"utf8"=>"✓", "authenticity_token"=>"NCT4NgS6ZvbqpcS4+CsoYI4pJurYzwsCyj5U6k3MTwSFqDpdLMX+XVFIpAP/pXD3ZDNr6T6mIOf58gUk6SEqOQ==", "recipe"=>{"rec_name"=>"s", "rec_description"=>"s", "ingredient_recipes_attributes"=>{"0"=>{"ingredient_id"=>"2", "quantity"=>"1"}, "1"=>{"ingredient_id"=>"1", "quantity"=>"1"}, "2"=>{"ingredient_id"=>"3", "quantity"=>"1"}}}, "commit"=>"Create Recipe"} (0.6ms) BEGIN SQL (4.6ms) INSERT INTO recipes ( created_at , updated_at ) VALUES ('2015-07-01 00:37:28', '2015-07-01 00:37:28') (2.1ms) COMMIT Redirected to http://localhost:3000/recipes/65 Completed 302 Found in 24ms (ActiveRecord: 7.3ms) 更新后没有错误,但是这里是我提交创建操作时得到的参数:参数:{“ utf8” =>“✓”,“ authenticity_token” =>“ NCT4NgS6ZvbqpcS4 + CsoYI4pJurYzwsCyj5U6k3MTwSFqDpdLMX + XVFIPZP6P3P6P3P6P3P6P0P6P0P6P0P6P0P0P6P0P6P0P0P0P1E0 “ => {” rec_name“ =>” s“,” rec_description“ =>” s“,” ingredient_recipes_attributes“ => {” 0“ => {” ingredient_id“ =>” 2“,” quantity“ =>” 1 “},” 1“ => {” ingredient_id“ =>” 1“,” quantity“ =>” 1“},” 2“ => {” ingredient_id“ =>” 3“,” quantity“ =>” 1 “}}}, ”提交“=>”创建配方“}(0.6ms)BEGIN SQL(4.6ms)INSERT INTO recipescreated_atupdated_at )VALUES( '2015年7月1日0时37分28秒',“2015年-07-01 00:37:28')(2.1ms)COMMIT重定向到http:// localhost:3000 / recipes / 65已完成302在24ms内找到(ActiveRecord:7.3ms)

Started GET "/recipes/65" for 127.0.0.1 at 2015-06-30 17:37:28 -0700 Processing by RecipesController#show as HTML Parameters: {"id"=>"65"} Recipe Load (4.7ms) SELECT recipes .* FROM recipes WHERE recipes . 从2015年6月30日17:37:28 -0700开始为127.0.0.1的GET“ / recipes / 65”,由RecipesController#show处理为HTML参数:{“ id” =>“ 65”}配方加载(4.7ms)选择recipes 。*从recipes选择recipes id = 65 LIMIT 1 Rendered recipes/show.html.erb within layouts/application (0.7ms) Completed 200 OK in 136ms (Views: 126.4ms | ActiveRecord: 4.7ms) id = 65 LIMIT 1在布局/应用程序中呈现的Recipes / show.html.erb(0.7ms)在136ms内完成200 OK(查看:126.4ms | ActiveRecord:4.7ms)

It seems everything is on the right way but I don't know why after render show action It doesn't show the attributes of the recipe I just added, and It also didn't create the record in the join table. 似乎一切都在正确的方向上,但是我不知道为什么在执行show show action之后它不显示我刚刚添加的配方的属性,并且它也没有在联接表中创建记录。

Please help me! 请帮我! Thanks so much 非常感谢

You have an error in your model: 您的模型有错误:

class Ingredient < ActiveRecord::Base
has_many :ingredient_recipes, inverse_of: :ingredient_recipes, autosave: true
has_many :recipes, :through => :ingredient_recipes

The following line is not correct. 以下行是不正确的。 An inverse relationship to itself is not valid: 与自身的逆关系无效:

has_many :ingredient_recipes, inverse_of: :ingredient_recipes, autosave: true

This is why you're getting the error: 这就是为什么出现错误的原因:

Unpermitted parameter: ingredient_recipe 不允许的参数:Ingredient_recipe

Next steps (Added) 后续步骤(已添加)

  • Remove the incorrect inverse_of relationship from the ingredient model 从成分模型中删除错误的inverse_of关系
  • Evaluate whether you need an inverse_of relationship and what it should do 评估您是否需要inverse_of关系以及它应该做什么
  • Only you know what your app needs to do, but if you need the original inverse_of ingredient_recipes, it should be here: 只有您知道您的应用程序需要做什么,但是如果您需要原始的inverse_of Ingredient_recipes,则应该在这里:
class IngredientRecipe < ActiveRecord::Base
  belongs_to :recipe, :inverse_of ingredient_recipes
  belongs_to :ingredient
  accepts_nested_attributes_for :ingredient
end

More debug advice: Remove "autosave" and create child record explicitly (Edit) 更多调试建议:删除“自动保存”并显式创建子记录(编辑)

You must first create the parent record successfully before adding the "belongs to" child. 您必须先成功创建父记录,然后才能添加“属于”子级。 Your autosave a parameter supposedly does this action, but it is not working for some reason, which you have to debug. 您的自动保存参数可以执行此操作,但是由于某种原因它无法工作,您必须对其进行调试。 To do this I suggest that you explicitly create an action on the child tables after you create your parent recipe record. 为此,我建议您在创建父配方记录后在子表上显式创建一个操作。

Once you get the parent and child records creating properly with explicit calls, then put the autosave back in the model, rollback the explicit creates and see if the parent save invokes the child save. 一旦使用显式调用正确创建了父记录和子记录,然后将自动保存回模型中,回滚显式创建的内容,并查看父存储是否调用了子存储。 I always use explicit saves because I want to control the process. 我总是使用显式保存,因为我想控制该过程。


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

相关问题 Rails / Active Record has_many通过关联 - 获取记录 - Rails / Active Record has_many through association - fetching a record Rails mutlipe has_many通过不同的模型到单个模型 - Rails mutlipe has_many through different models to single model Rails 4:通过模型建立两个has_many的模型关系和索引 - Rails 4: model relationships and indexing for two has_many through models 在Rails 3.1中通过has_many实现has_many - Has_many through a has_many in Rails 3.1 创建餐厅菜单我应该使用has_many通过或habtm关联吗? - Creating a Restaurant Menu should I use a has_many through or habtm association? rails 4通过关联在has_many上使用includes时保留连接对象顺序 - rails 4 preserve join object order when using includes on a has_many through association 链接has_many:through关联中的where子句(Rails 4.1.0.rc1) - Chained where clauses on has_many :through association (Rails 4.1.0.rc1) Rails 4-如何通过has_many关联在同一列上具有多个条件来查询集合? - Rails 4 - how do I query on a collection through a has_many association with multiple conditions on the same columns? 通过has_many:through关联检索ID的优化方法 - Optimized way to retrieve IDs through has_many :through association Rails has_many:通过未定义的方法 - Rails has_many :through, undefined method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM