Ruby-on-rails 如何允许具有强参数的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16549382/
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-02 21:59:34  来源:igfitidea点击:

how to permit an array with strong parameters

ruby-on-railsarraysstrong-parameters

提问by Leahcim

I have a functioning Rails 3 app that uses has_many :through associations which is not, as I remake it as a Rails 4 app, letting me save ids from the associated model in the Rails 4 version.

我有一个功能正常的 Rails 3 应用程序,它使用 has_many :through 关联,这不是,因为我将它改造成 Rails 4 应用程序,让我从 Rails 4 版本中的关联模型中保存 ID。

These are the three relevant models are the same for the two versions.

这些是三个相关模型对于两个版本是相同的。

Categorization.rb

分类.rb

class Categorization < ActiveRecord::Base

  belongs_to :question
  belongs_to :category
end

Question.rb

问题.rb

has_many :categorizations
has_many :categories, through: :categorizations

Category.rb

类别.rb

has_many :categorizations
has_many :questions, through: :categorizations

In both apps, the category ids are getting passed into the create action like this

在这两个应用程序中,类别 ID 被传递到这样的创建操作中

  "question"=>{"question_content"=>"How do you spell car?", "question_details"=>"blah ", "category_ids"=>["", "2"],

In the Rails 3 app, when I create a new question, it inserts into questions table and then into the categorizations table

在 Rails 3 应用程序中,当我创建一个新问题时,它会插入到问题表中,然后插入到分类表中

 SQL (82.1ms)  INSERT INTO "questions" ("accepted_answer_id", "city", "created_at", "details", "province", "province_id", "question", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)  [["accepted_answer_id", nil], ["city", "dd"], ["created_at", Tue, 14 May 2013 17:10:25 UTC +00:00], ["details", "greyound?"], ["province", nil], ["province_id", 2], ["question", "Whos' the biggest dog in the world"], ["updated_at", Tue, 14 May 2013 17:10:25 UTC +00:00], ["user_id", 53]]
  SQL (0.4ms)  INSERT INTO "categorizations" ("category_id", "created_at", "question_id", "updated_at") VALUES (?, ?, ?, ?)  [["category_id", 2], ["created_at", Tue, 14 May 2013 17:10:25 UTC +00:00], ["question_id", 66], ["updated_at", Tue, 14 May 2013 17:10:25 UTC +00:00]]

In the rails 4 app, after it processes the parameters in QuestionController#create, I'm getting this error in the server logs

在 rails 4 应用程序中,在处理 QuestionController#create 中的参数后,我在服务器日志中收到此错误

Unpermitted parameters: category_ids

and the question is only getting inserted into the questions table

并且问题只是被插入到问题表中

 (0.2ms)  BEGIN
  SQL (67.6ms)  INSERT INTO "questions" ("city", "created_at", "province_id", "question_content", "question_details", "updated_at", "user_id") VALUES (, , , , , , ) RETURNING "id"  [["city", "dd"], ["created_at", Tue, 14 May 2013 17:17:53 UTC +00:00], ["province_id", 3], ["question_content", "How's your car?"], ["question_details", "is it runnign"], ["updated_at", Tue, 14 May 2013 17:17:53 UTC +00:00], ["user_id", 12]]
   (31.9ms)  COMMIT

Although I am not storing the category_ids on the Questions model, I set category_ids as a permitted parameter in the questions_controller

虽然我没有将 category_ids 存储在 Questions 模型中,但我将 category_ids 设置为 questions_controller 中允许的参数

   def question_params

      params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids)
    end

Can anyone explain how I'm supposed to save the category_ids? Note, there is no create action in the categories_controller.rb of either app.

谁能解释我应该如何保存category_ids?请注意,任一应用程序的 category_controller.rb 中都没有创建操作。

These are the three tables that are the same in both apps

这是两个应用程序中相同的三个表

 create_table "questions", force: true do |t|
    t.text     "question_details"
    t.string   "question_content"
    t.integer  "user_id"
    t.integer  "accepted_answer_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "province_id"
    t.string   "city"
  end

 create_table "categories", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "categorizations", force: true do |t|
    t.integer  "category_id"
    t.integer  "question_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

Update

更新

This is the create action from the Rails 3 app

这是来自 Rails 3 应用程序的创建操作

  def create
      @question = Question.new(params[:question])
      respond_to do |format|
      if @question.save
        format.html { redirect_to @question, notice: 'Question was successfully created.' }
        format.json { render json: @question, status: :created, location: @question }
      else
        format.html { render action: "new" }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
end

This is the create action from the Rails 4 app

这是来自 Rails 4 应用程序的创建操作

   def create
      @question = Question.new(question_params)

       respond_to do |format|
      if @question.save
        format.html { redirect_to @question, notice: 'Question was successfully created.' }
        format.json { render json: @question, status: :created, location: @question }
      else
        format.html { render action: "new" }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
    end

This is the question_params method

这是 question_params 方法

 private
    def question_params 
      params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids)
    end

回答by Leahcim

This https://github.com/rails/strong_parametersseems like the relevant section of the docs:

这个https://github.com/rails/strong_parameters似乎是文档的相关部分:

The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile.

To declare that the value in params must be an array of permitted scalar values map the key to an empty array:

params.permit(:id => [])

允许的标量类型为 String、Symbol、NilClass、Numeric、TrueClass、FalseClass、Date、Time、DateTime、StringIO、IO、ActionDispatch::Http::UploadedFile 和 Rack::Test::UploadedFile。

要声明 params 中的值必须是允许的标量值数组,请将键映射到空数组:

params.permit(:id => [])

In my app, the category_ids are passed to the create action in an array

在我的应用程序中,category_ids 以数组的形式传递给 create 操作

"category_ids"=>["", "2"],

Therefore, when declaring strong parameters, I explicitly set category_ids to be an array

因此,在声明强参数时,我明确将 category_ids 设置为数组

params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids => [])

Works perfectly now!

现在完美运行!

(IMPORTANT:As @Lenart notes in the comments, the array declarations must be at the endof the attributes list, otherwise you'll get a syntax error.)

重要提示:正如@Lenart 在注释中所指出的,数组声明必须位于属性列表的末尾,否则会出现语法错误。)

回答by Brian

If you want to permit an array of hashes(or an array of objectsfrom the perspective of JSON)

如果你想允许一个哈希数组(或an array of objects从 JSON 的角度)

params.permit(:foo, array: [:key1, :key2])

2 points to notice here:

这里要注意2点:

  1. arrayshould be the last argument of the permitmethod.
  2. you should specify keys of the hash in the array, otherwise you will get an error Unpermitted parameter: array, which is very difficult to debug in this case.
  1. array应该是方法的最后一个参数permit
  2. 你应该在数组中指定散列的键,否则你会得到一个错误Unpermitted parameter: array,在这种情况下很难调试。

回答by Matias Seguel

It should be like

它应该像

params.permit(:id => [])

Also since rails version 4+ you can use:

此外,从 Rails 版本 4+ 开始,您可以使用:

params.permit(id: [])

回答by Fellow Stranger

If you have a hash structure like this:

如果您有这样的哈希结构:

Parameters: {"link"=>{"title"=>"Something", "time_span"=>[{"start"=>"2017-05-06T16:00:00.000Z", "end"=>"2017-05-06T17:00:00.000Z"}]}}

Then this is how I got it to work:

然后这就是我让它工作的方式:

params.require(:link).permit(:title, time_span: [[:start, :end]])

回答by Daniel Duque

I can't comment yet but following on Fellow Stranger solution you can also keep nesting in case you have keys which values are an array. Like this:

我还不能发表评论,但是按照 Fellow Stranger 解决方案,你也可以继续嵌套,以防你有一个值为数组的键。像这样:

filters: [{ name: 'test name', values: ['test value 1', 'test value 2'] }]

This works:

这有效:

params.require(:model).permit(filters: [[:name, values: []]])