我有一个试图从中检索数据数组的模型,并且我不需要将数据实例化到Ruby对象中。实际上,这只是在我的代码中引入了一个额外的步骤来遍历对象,并生成一个包含我需要的数据的新数组。
示例:
class Book
#has attribute in database title
end我想生成一个数组,其中包含数据库中所有图书的所有标题。做这件事最好的方法是什么?
发布于 2016-04-17 14:57:24
您可以使用gem pluck_to_hash https://github.com/girishso/pluck_to_hash
它的工作方式类似于pluck,但返回散列数组
Post.limit(2).pluck_to_hash(:id, :title)
#
# [{:id=>213, :title=>"foo"}, {:id=>214, :title=>"bar"}]
#https://stackoverflow.com/questions/2393412
复制相似问题