【问题标题】:Unable to add to params hash using merge无法使用合并添加到参数哈希
【发布时间】:2014-02-04 18:47:18
【问题描述】:

我似乎无法在我的参数哈希中添加新值。我正在尝试将此 actor_id 键添加到参数,但这不起作用:

params.merge(:actor_id => 2)

当我在合并前后使用 logger.debug 时,我看不到我的 actor_id 键。如何添加到params

【问题讨论】:

  • merge 不会改变哈希值。
  • @JustinWood 谢谢,贾斯汀。我将如何添加到参数?
  • 在许多情况下,您可以添加一个 bang (!) 来改变值。在这种情况下,merge! 将修改哈希。

标签: ruby-on-rails


【解决方案1】:

这是因为 ActiveSupport::HashWithIndifferentAccess 中的方法 merge 并没有修改接收者,而是返回一个新的哈希值,其访问权限与合并结果无关。

因为 cmets 建议使用合并!或使用别名更新。

ActiveController::Parameters 继承自 ActiveSupport::HashWithIndifferentAccess

    # This method has the same semantics of +update+, except it does not
    # modify the receiver but rather returns a new hash with indifferent
    # access with the result of the merge.
    def merge(hash, &block)
      self.dup.update(hash, &block)
    end

【讨论】:

    【解决方案2】:

    试试这个

    params.merge!(actor_id: 2)

    它会在我们使用 ! 时修改参数本身!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      • 1970-01-01
      • 2015-08-16
      • 1970-01-01
      • 2020-07-24
      • 2012-09-03
      • 1970-01-01
      相关资源
      最近更新 更多