[英]How to merge missing params fields from db to a params hash in rails
Lets say the app recieves a param hash like this 可以说应用程序收到了这样的参数哈希
Parameters: {"utf8"=>"✓", "authenticity_token"=>"sjfsj", "user"=>{"name"=>"Joe", "mobile"=>"12345678"}, "commit"=>"Save Changes"}
and this is the user
model 这是
user
模型
{name: "value", mobile: "value", email: "value", many_others: "other_values" }
What am trying to do is create
a new hash
with all fields combined( params + missing_fields_from_db
). 试图做的是
create
一个new hash
,将所有字段组合在一起( params + missing_fields_from_db
)。 So if the params has some missing keys it will be taken from model add to the new hash. 因此,如果参数缺少一些键,则将从模型添加到新哈希中。
Like this: 像这样:
{name: "Joe", mobile: "12345678", email: "value", many_others: "other_values" }
Is there a method available for that in ruby || rails
在
ruby || rails
有没有可用的方法? ruby || rails
? ruby || rails
?
Thank you 谢谢
You are looking for a Hash#merge
or Hash#reverse_merge
. 您正在寻找
Hash#merge
或Hash#reverse_merge
。 Difference: 区别:
a = { foo: 1, bar: 2, baf: 3 }
b = { foo: 2, bar: 1, baz: 1 }
a.merge(b)
#=> {:foo=>2, :bar=>1, :baf=>3, :baz=>1}
a.reverse_merge(b)
#=> {:foo=>1, :bar=>2, :baz=>1, :baf=>3}
Note, that Hash#merge
is a pure Ruby method, Hash#reverse_merge
comes from Rails. 注意,
Hash#merge
是纯Ruby方法, Hash#reverse_merge
来自Rails。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.