Rails 4: 强参数和标量数组必须在允许的最后列出吗?

Rails 4: strong parameters and array of scalars must be listed last on permit?

问题代码版本见people_controller#person_params方法:

# person.rb
class Person < ActiveRecord::Base
  # Attributes:
  # - names (string)
  # - age (integer)

  # Combine: ["a", "b", "c", ...] => "a,b,c"
  def names=(values)
    self[:names] = values.join(",") if values.present?
  end
end

# people_controller.rb
class PeopleController < ApplicationController
  def create
    @record = Record.new(person_params)
    @record.save!
  end

  def person_params
    params.require(:person).permit(
      # Works fine
      :age,
      names: []

      # Works fine
      { names: [] },
      :age

      # Does not work (SyntaxError)
      names: [],
      :age
    )
  end
end

问题是,为什么 names 标量数组在开头列出而不将其包装为散列时不起作用?

http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters 文档示例不使用散列包装标量数组,但它们也不是非常复杂的示例。

这是 strong_parameters 的预期行为吗?

这不是 strong_params 的事情,而是 ruby 如何读取属性列表。在 Ruby 中,当它是 方法的最后一个参数时,您只能省略散列周围的花括号 ,因此调用:

any_method(arg1, arg2, key: value, foo: :bar)

读作:

any_method(arg1, arg2, { key: value, foo: :bar })

如果散列不是最后一个参数,则不能省略括号,因此:

any_method(arg1, key: value, arg2)

会引发语法错误。