考虑一个to_h
定义为类方法的类,用于将一些数据提取到哈希中......
class User
self.to_h
pluck(:name, :email)
end
end
irb> User.to_h
{"joe"=>"joe@joe.com"}
在 ruby 2.3.8 和 Rails 4.1.8 下,这很好用。
在 ruby 2.5.0 和 Rails 5.2.4.5 下,to_h
如果在类上调用,则可以工作,但不能在范围内调用...
irb> User.to_h
{"joe"=>"joe@joe.com"}
irb> User.all.to_h
TypeError (wrong element type Timer (expected array))
这是 Rails 还是 Ruby 问题?显然 ActiveRecord::Relation 没有使用 class level to_h
。