Rails:Rails 5 中不允许的参数 [英] Rails: Unpermitted parameter in Rails 5

查看:48
本文介绍了Rails:Rails 5 中不允许的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

我的课程:

class Project < ApplicationRecord
  has_many :project_criteria
  accepts_nested_attributes_for :project_criteria
end

class ProjectCriterium < ApplicationRecord
  belongs_to :project
end

项目控制器:

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

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

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

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 # <-----------

注意:

顺便说一句,我已经尝试使用 criterium 而不是 criteria(- 在我看来 - 是正确的,因为它应该复数形式)在 has_manyaccepts_nested_attributes_for 中,但它也不起作用.

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

有人对此有解决方案吗?

Does someone have a solution for this?

推荐答案

给您带来问题的不是标准"这个词的屈折变化(尽管您可以添加自定义屈折词以获得您喜欢的单复数版本,如果您很想要).

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.

更改您当前的参数:

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]} )

这篇关于Rails:Rails 5 中不允许的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆