ruby-on-rails - 修改参数嵌套哈希的最佳方法是什么?
问题描述
修改参数哈希中的某些值的最佳方法是什么?例如,这是 params 哈希。
{"utf8"=>"✓", "authenticity_token"=>"asdasdasd/Wi71c4U3aXasdasdasdpbyMZLYo1sAAmssscQEkv0WsWBDyslcWJxUZ2pPKOQFmJoVZw==", "user_api"=>{"user"=>"asdak", "name"=>"asdada", "friends_attributes"=>{"1566720653776"=>{"_destroy"=>"false", "player_name"=>"asda", "player_type"=>"backside", "user_interest"=>"cricket,football,basketball"}, "1566720658089"=>{"_destroy"=>"false", "player_name"=>"asdad", "player_type"=>"forward", "user_interest"=>"table_tennis,chess"}}}, "commit"=>"Save User Data"}
所以从上面的参数中,我需要将user_options的值修改为一个数组。
params.each do |key, user_api_hash|
if key == "user_api"
user_api_hash.each do |key, friend_hash|
if key == "friends_attributes"
friend_hash.each do |key, value|
value["user_interest"] = value["user_interest"].split(',')
end
end
end
end
end
我发现这种方法效率不高,因为我必须迭代指数次,具体取决于散列的数量。谁能建议我一个更好的方法来做到这一点?
预先感谢您的帮助。
解决方案
如果你想修改它们而不是返回一个新对象:
(params.dig(:user_api, :friends_attributes) || []).each do |_, attributes|
attributes['user_interest'] = attributes['user_interest'].split(',')
end
dig
可以访问散列内部和其中其他散列内部的键。- 如果某个键不存在,那么它将返回 nil,在这种情况下使用一个空数组,它将迭代 0 次。
- 在用户属性中,您可以通过简单的分配来修改它们。