Rails Object to hash Ask Question

Rails Object to hash Ask Question

I have the following object that has been created

@post = Post.create(:name => 'test', :post_number => 20, :active => true)

Once this is saved, I want to be able to get the object back to a hash, e.g. by doing somthing like:

@object.to_hash

How is this possible from within rails?

ベストアンサー1

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

おすすめ記事