gpt4 book ai didi

ruby-on-rails - 为什么 Rails 中的强参数顺序很重要?

转载 作者:行者123 更新时间:2023-12-02 03:35:14 24 4
gpt4 key购买 nike

在我的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

错误:

syntax error, unexpected ',', expecting => ..., :name], :product_category_id, attr_val_ids: []) ... ^

为什么会发生这种情况?我已经坚持了很长时间了:/


产品模型.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

产品类别.rb

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

has_many :product_models
end

最佳答案

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

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

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

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 会将两者视为参数、散列、参数、散列并且能够处理。

关于ruby-on-rails - 为什么 Rails 中的强参数顺序很重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50436808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com