Ruby:将一组 ActiveRecord 对象分组到一个散列中 [英] Ruby: group an array of ActiveRecord objects in a hash

查看:38
本文介绍了Ruby:将一组 ActiveRecord 对象分组到一个散列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 ActiveRecord 对象数组分组到一个散列中,该散列具有易于在 SQL 语句后查询的接口,如下所示:

I'd like to group an array of ActiveRecord objects into a hash with an interface that's simple to query after an SQL statement that looks like the following:

SELECT name,value from foo where name IN ('bar', 'other_bar') LIMIT 2;

在那个查询之后,我想要一个我可以去的哈希:

After that query, I want a hash where I can go:

foo[:bar] # output: value1
foo[:other_bar] # output: value2

使用 ActiveRecord 收集对象并将它们分组以便我可以使用上面的界面的最佳方法是什么?

What's the best way to collect the objects with ActiveRecord and group them so I can use the interface above?

推荐答案

In Rails 2

foos = Foo.all :select => "name, value",
               :conditions => ["name in (?)", %w(bar other_bar)],
               :limit => 2

在 Rails 3 中

In Rails 3

foos = Foo.where("name in (?)", %w(bar other_bar)).select("name, value").limit(2)

然后

foo = Hash[foos.map { |f| [f.name.to_sym, f.value] }]

foo = foos.inject({}) { |h, f| h[f.name.to_sym] = f.value; h }

或在 Ruby 1.9 中

or in Ruby 1.9

foo = foos.each_with_object({}) { |f, hash| hash[f.name.to_sym] = f.value }

这篇关于Ruby:将一组 ActiveRecord 对象分组到一个散列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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