Rails 6, has added a new utility method each_value
on ActionController::Parameters.
This method as the name suggests iterates over and
yields each value of the ActionController::Parameters
just like Hash#each_value
.
Hash#each_value vs ActionController::Parameters#each_value
It’s different from Hash#each_value
in that
it converts all the hashes in values to ActionController::Parameters
object
before yielding the values to block, instead of simply returning the value.
Example
Consider the example below, we define a ActionController::Parameters
with user profile details
params = ActionController::Parameters.new({
name: {
first: "Narendra",
last: "Rajput"
},
gender: "Male",
})
=> <ActionController::Parameters {"name"=>{"first"=>"Narendra", "last"=>"Rajput"}, "gender"=>"Male"} permitted: false>
Now lets add another regular hash object to params
params[:social_profiles] = {
twitter: "https://twitter.com/HiSaeloun",
github: "https://github.com/saeloun"
}
=> {:twitter=>"https://twitter.com/HiSaeloun", :github=>"https://github.com/saeloun"}
Now if we iterate over the params
with ActionController::Parameters#each_value
params.each_value do |value|
puts value.inspect
end
<ActionController::Parameters {"first"=>"Narendra", "last"=>"Rajput"} permitted: false>
"Male"
<ActionController::Parameters {"twitter"=>"https://twitter.com/HiSaeloun", "github"=>"https://github.com/saeloun"} permitted: false>
As you can see the social_profiles
in the params is a Hash. But in the each_value
block its converted to ActionController::Parameters
.
This is helpful for consistent parameters object access.