[英]How to merge Hash with Rails controller's params?
Given a Hash with symbol keys, eg: { name: 'Jeff' }
, what would be the easiest method to merge it with controller's params
? 给定带有符号键的哈希,例如:
{ name: 'Jeff' }
,将其与控制器params
合并的最简单方法是什么?
Using the straightforward merge
produces the wrong result: 使用直接
merge
会产生错误的结果:
> {a: 1}.merge(HashWithIndifferentAccess.new(a: 2, b: 3))
=> {:a=>1, "a"=>2, "b"=>3}
The desired result is {:a=>2, :b=>3}
. 期望的结果是
{:a=>2, :b=>3}
。
There are 2 possible ways to merge a Hash with the params of rails: 有两种将Hash与rails的参数合并的方法:
HashWithIndifferentAccess.new(YOUR_HASH).merge(params)
or vice versa HashWithIndifferentAccess.new(YOUR_HASH).merge(params)
或反之亦然 YOUR_HASH.with_indifferent_access.merge(params)
or vice versa YOUR_HASH.with_indifferent_access.merge(params)
,反之亦然 The order matters in both variants. 顺序在两个变体中都重要。 The parameter of
merge(XXX)
overrides the settings of your Hash which called the merge
method. merge(XXX)
的参数merge(XXX)
覆盖哈希的设置,该设置称为merge
方法。 If you want it vice versa, simply swap them. 反之亦然,只需将它们交换即可。
FYI: Rails adds a new method to the Hash class: with_indifferent_access
-> Rails Doc 仅供参考:Rails向Hash类添加了一个新方法:
with_indifferent_access
> Rails Doc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.