Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there some Ruby on Rails method to convert a model object into a HASH structure?

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?

like image 834
mlzboy Avatar asked Nov 11 '10 11:11

mlzboy


2 Answers

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.

like image 73
Mirko Avatar answered Nov 15 '22 21:11

Mirko


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

like image 31
Gagan Avatar answered Nov 15 '22 20:11

Gagan