I have a model User
u=User.find(1)
How do I get u
instance converted into a hash? Is there some built-in method to do this?
Answer is here on SO: Rails Object to hash (use .attributes
method)
I needed this for rspecing update method, since you have to give it a hash as param.
You can use as_json to achieve what you want.
@object = User.find(1)
@object.as_json
as_json has very flexible way to configure complex object according to model relations
EXAMPLE
We can exclude columns like this too
@object.as_json({except: [:created_at, :updated_at]})
Official documentation for as_json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With