Ruby-on-rails Rails 5 中不允许的参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39046532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:29:08  来源:igfitidea点击:

Unpermitted parameter in Rails 5

ruby-on-railsrubyruby-on-rails-5

提问by developer033

First of all I want simply get an object inside the current object that I'm sending to my backend.

首先,我只想在我发送到后端的当前对象中获取一个对象。

I have this simple JSON(generated from a form):

我有这个简单的JSON(从表单生成):

{
  "name": "Project 1",
  "project_criteria": [
    {
      "name": "Criterium 1",
      "type": "Type 1",
      "benefit": "1"
    },
    {
      "name": "Criterium 2",
      "type": "Type 2",
      "benefit": "3"
    }
  ]
}

My classes:

我的classes

class Project < ApplicationRecord
  has_many :project_criteria
  accepts_nested_attributes_for :project_criteria
end

class ProjectCriterium < ApplicationRecord
  belongs_to :project
end

ProjectsController:

项目控制器:

def project_params
  params.require(:project).permit(:name,  project_criteria: [] )
end

But I still can't access project_criteriaparameter as you can see below:

但是我仍然无法访问project_criteria参数,如下所示:

Started POST "/projects" for 127.0.0.1 at 2016-08-19 16:24:03 -0300
Processing by ProjectsController#create as HTML
  Parameters: {"project"=>{"name"=>"Project 1", "project_criteria"=>{"0"=>{"benefit"=>"1", "name"=>"Criterium 1", "type"=>"Type 1"}, "1"=>{"benefit"=>"3", "name"=>"Criterium 2", "type"=>"Type 2"}}}}
Unpermitted parameter: project_criteria # <-----------

Note:

笔记:

By the way, I already tried to use criteriuminstead of criteria(which - in my opinion -is the correct since it should be pluralized) in has_manyand accepts_nested_attributes_for, but it also doesn't work.

顺便说一下,我已经尝试在and 中使用标准而不是标准在我看来,这是正确的,因为它应该复数形式),但它也不起作用。has_manyaccepts_nested_attributes_for

Does someone have a solution for this?

有人对此有解决方案吗?

回答by MarsAtomic

It's not the inflection of the word "criteria" that's giving you problems (although you can add a custom inflector to get the singular and plural versions you prefer if you really want).

给您带来问题的不是“标准”一词的变形(尽管您可以添加自定义变形器来获得您喜欢的单数和复数版本,如果您真的想要的话)。

The issue is that you have to explicitly permit the fields of nested objects.

问题是您必须明确允许嵌套对象的字段。

Change your current params:

更改您当前的参数:

params.require(:project).permit(:name,  project_criteria: [] )

To this (for a single nested object):

为此(对于单个嵌套对象):

params.require(:project).permit(:name,  project_criteria: [:name, :type, :benefit] )

Your case is somewhat compounded by the fact that you're dealing with multiple nested objects, so you'll have to pass a hash instead:

由于您正在处理多个嵌套对象,因此您的情况有些复杂,因此您必须改为传递哈希:

params.require(:project).permit(:name,  { project_criteria: [:name, :type, :benefit]} )