Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

ruby - Rails: Unpermitted parameter in Rails 5

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):

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

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

Note:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...