小编典典

Rails 要散列的对象

all

我有以下已创建的对象

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

保存后,我希望能够将对象恢复为哈希,例如通过执行以下操作:

@object.to_hash

这怎么可能在 Rails 内实现?


阅读 84

收藏
2022-09-02

共1个答案

小编典典

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

@post.attributes

请注意,ActiveModel::AttributeSet.to_hash每次调用它时都会调用它,因此如果您需要多次访问散列,则应将其缓存在局部变量中:

attribs = @post.attributes
2022-09-02