将 Active Record 集转换为哈希数组 [英] Convert Active Record set into an array of hashes

查看:50
本文介绍了将 Active Record 集转换为哈希数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了这个...

如何将 activerecord 结果转换为数组散列

并且想要创建一种方法,允许我将任何范围或非范围的记录集转换为哈希数组.我将此添加到我的模型中:

and wanted to create a method that would allow me to turn any scoped or non-scoped record set into an array of hashes. I added this to my model:

 def self.to_hash
   to_a.map(&:serializable_hash)
 end

但是,我收到此错误.

NameError: undefined local variable or method `to_a' for #<Class:0x007fb0da2f2708>

有什么想法吗?

推荐答案

你可能也需要调用 all 来解决这个问题.仅 to_a 可以在范围或现有结果集(例如 User.active.to_hash)上正常工作,但不能直接在模型上(例如 User.to_hash).使用 all.to_a 将适用于这两种情况.

You probably need to call all on that too. Just the to_a would work fine on a scope or existing result set (e.g. User.active.to_hash) but not directly on the model (e.g. User.to_hash). Using all.to_a will work for both scenarios.

def self.to_hash
  all.to_a.map(&:serializable_hash)
end

请注意,all.to_a 有点重复,因为 all 已经返回一个数组,但在 Rails 4 中它是必要的.

Note that the all.to_a is a little duplicative since all already returns an array, but in Rails 4 it will be necessary.

这篇关于将 Active Record 集转换为哈希数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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