Damon Yuan
Damon Yuan

Reputation: 3803

strange behavior of to_h method in ruby

I have condition var which need to be converted to hash but I always get an empty hash and I do not know why...The debug info is as follows.

0> p conditions
App 3069 stdout: {"email"=>"[email protected]"}
=> {"email"=>"[email protected]"}

0> p conditions.class
App 3069 stdout: ActionController::Parameters
=> ActionController::Parameters

0> p conditions.to_h
App 3069 stdout: {}
=> {}

And I tried to_hash, it just behaves as espected!!!really strange!!!

Upvotes: 0

Views: 1677

Answers (1)

Prakash Murthy
Prakash Murthy

Reputation: 13067

Nothing strange about it; p conditions.to_h is returning {} correctly as none of the keys are marked as permitted.

Take a look at the documentation for the method: http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-to_h

to_h()

Returns a safe Hash representation of this parameter with all unpermitted keys removed.

Try setting a key as permitted as follows:

> permitted_conditions = conditions.permit(:email)
> permitted_conditions.to_h
=> {"email"=>"[email protected]"}

to_unsafe_h has the behavior you were originally looking for.

Upvotes: 4

Related Questions