要散列的 Rails 对象 [英] Rails Object to hash

查看:31
本文介绍了要散列的 Rails 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了以下对象

@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

这在 Rails 中怎么可能?

How is this possible from within rails?

推荐答案

如果您只查找属性,那么您可以通过以下方式获取它们:

If you are looking for only attributes, then you can get them by:

@post.attributes

请注意,这会调用 ActiveModel::AttributeSet.to_hash 每次调用它,所以如果你需要多次访问散列,你应该将它缓存在一个局部变量中:

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

这篇关于要散列的 Rails 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆