Rails Object to hash
If you are looking for only attributes, then you can get them by:
@post.attributes
Note that this calls ActiveModel::AttributeSet.to_hash
every time you invoke it, so if you need to access the hash multiple times you should cache it in a local variable:
attribs = @post.attributes
In most recent version of Rails (can't tell which one exactly though), you could use the as_json
method :
@post = Post.first
hash = @post.as_json
puts hash.pretty_inspect
Will output :
{
:name => "test",
:post_number => 20,
:active => true
}
To go a bit further, you could override that method in order to customize the way your attributes appear, by doing something like this :
class Post < ActiveRecord::Base
def as_json(*args)
{
:name => "My name is '#{self.name}'",
:post_number => "Post ##{self.post_number}",
}
end
end
Then, with the same instance as above, will output :
{
:name => "My name is 'test'",
:post_number => "Post #20"
}
This of course means you have to explicitly specify which attributes must appear.
Hope this helps.
EDIT :
Also you can check the Hashifiable gem.