将 Active Record 集转换为哈希数组 [英] Convert Active Record set into an array of hashes
问题描述
我看到了这个...
并且想要创建一种方法,允许我将任何范围或非范围的记录集转换为哈希数组.我将此添加到我的模型中:
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屋!