【问题标题】:Why does strong params order in Rails matter?为什么 Rails 中的强参数顺序很重要?
【发布时间】:2018-05-20 16:09:55
【问题描述】:

在我的product_model_controller.rb 中,强参数有以下代码:

  def product_model_params
    params.require(:product_model)
          .permit(:name, :product_category_id, 
                  product_category_attributes: [:id, :name], attr_val_ids: [])
  end

就目前而言,它工作正常。但是,如果我更改参数的顺序,它就会停止工作。示例:

  def product_model_params
    params.require(:product_model)
          .permit(:name, product_category_attributes: [:id, :name],
                  :product_category_id, attr_val_ids: [])
  end

错误:

语法错误,意外 ',',期待 => ..., :name], :product_category_id, attr_val_ids: []) ... ^

为什么会这样?我已经坚持了很长时间了:/


product_model.rb

class ProductModel < ApplicationRecord
  validates :name, presence: true
  validates :name, uniqueness: true

  has_many :products
  has_many :product_model_attr_vals
  has_many :attr_vals, through: :product_model_attr_vals
  has_many :attrs, through: :attr_vals

  belongs_to :product_category

  accepts_nested_attributes_for :product_model_attr_vals
  accepts_nested_attributes_for :product_category
end

product_category.rb

class ProductCategory < ApplicationRecord
  validates :name, presence: true
  validates :name, uniqueness: true

  has_many :product_models
end

【问题讨论】:

    标签: ruby-on-rails forms nested-forms strong-parameters nested-form-for


    【解决方案1】:

    这不是强参数的问题,而是 Ruby 如何解析方法签名和哈希。稍微抽象一下你的第一个例子是这样的:

    some_method(arg1, arg2, key1: val1, key2: val2)
    

    Ruby 将识别隐式 trailing 哈希并在内部将其表示为:

    some_method(arg1, arg2, {key1: val1, key2: val2})
    

    此仅适用于最正确的类似散​​列的参数。在您的第二个示例中,您已经这样做了:

    some_method(arg1, key1: val1, arg2, key2: val2)
    

    Ruby 不知道该怎么做。它将key2 参数转换为一个哈希值,然后留下一个参数、一个看起来像命名参数的东西和一个参数。而且它不喜欢那样。

    你可以通过这样做来修复它:

    some_method(arg1, {key1: val1}, arg2, key2: val2)
    

    甚至这个:

    some_method(arg1, {key1: val1}, arg2, {key2: val2})
    

    Ruby 将两者都视为参数、散列、参数、散列并且能够处理。

    【讨论】:

    • 你好,@Philip。非常感谢您的详细解释:)。我刚刚在这里尝试过,效果很好\o/
    猜你喜欢
    • 1970-01-01
    • 2015-03-10
    • 2020-11-22
    • 2022-01-06
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多