如何允许具有强参数的数组


269

我有一个运行正常的Rails 3应用程序,它使用has_many:through关联,但不是,因为我将其重新制作为Rails 4应用程序,让我从Rails 4版本中的关联模型中保存了ID。

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

分类

class Categorization < ActiveRecord::Base

  belongs_to :question
  belongs_to :category
end

Question.rb

has_many :categorizations
has_many :categories, through: :categorizations

Category.rb

has_many :categorizations
has_many :questions, through: :categorizations

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

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

在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]]

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

Unpermitted parameters: category_ids

问题只是插入到问题表中

 (0.2ms)  BEGIN
  SQL (67.6ms)  INSERT INTO "questions" ("city", "created_at", "province_id", "question_content", "question_details", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5, $6, $7) 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

尽管我没有将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

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

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

 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

更新资料

这是来自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

这是来自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

这是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

这两个应用程序中的创建动作是什么样的?
尼克,

@bennick我添加了两个创建动作。谢谢
Leahcim

Answers:


527

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

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

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

params.permit(:id => [])

在我的应用中,category_ids传递给数组中的create操作

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

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

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

现在工作完美!

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


105
我还注意到,数组的声明应位于属性列表的末尾。否则,我会收到语法错误syntax error, unexpected ')', expecting =>
Lenart

45
数组声明(嵌套参数)最后的原因是ActionController :: Parameters.permit希望每个参数都是哈希或符号。Ruby magic会将方法调用结束时的所有键值对s 转换为一个哈希,但是如果您在方法调用中将符号与键/值对混合使用,Ruby将不知道该怎么做。
sameers

7
如果category_ids不是数组(例如,发送了一个字符串),那么rails完全会发疯并引发a ERROR TypeError: expected Array (got String) for param `category_ids'是Rails中的错误吗?编辑:是的,它是:github.com/rails/rails/issues/11502
Dominik Goltermann

4
@Lenart谢谢,我以为我快疯了。这至少应该出现在strong_params自述文件中
Sebastialonso

3
@Lenart如果想避免语法错误,可以将其添加为哈希。params.permit(:foo, { bar: [] }, :zoo)
Foo Bar Zoo

99

如果要允许散列数组(或an array of objects从JSON的角度来看)

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

这里要注意2点:

  1. array应该是方法的最后一个参数permit
  2. 您应该在数组中指定哈希的键,否则会得到一个error Unpermitted parameter: array,在这种情况下很难调试。

和不支持数组数组(尚未):github.com/rails/rails/issues/23640
Andrei Dziahel

11
array不必放在最后,但是您需要确保您具有有效的Ruby。params.permit(:foo, array: [:key1, :key2], :bar)将不是有效的ruby,因为解释器希望在第一组之后使用hash key:value对。要拥有有效的Ruby,您需要params.permit(:foo, {array: [:key1, :key2]}, :bar)
mastaBlasta

你是冠军!
Lollypop

22

应该像

params.permit(:id => [])

此外,由于Rails版本4+,您可以使用:

params.permit(id: [])

12
请不要将数组作为允许方法的最后一个参数
Matias Elorriaga,

3
您所说的适用于Rails v4 +的哈希语法实际上是Ruby 1.9及更高版本中可用的语法,而不是Rails框架(尽管Rails 4需要Ruby 1.9.3或更高版本)
MegaTux

11

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

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

然后这就是我如何使其工作的方式:

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

6

我还不能发表评论,但是在Fellow Stranger解决方案之后,您还可以保留嵌套,以防您拥有键值是数组的情况。像这样:

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

这有效:

params.require(:model).permit(filters: [[:name, values: []]])
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.