简体   繁体   English

如何将缺少的参数字段从db合并到Rails中的参数哈希

[英]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#mergeHash#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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM