我想将一个 ActiveRecord 对象数组分组到一个散列中,该散列具有一个易于在 SQL 语句之后查询的接口(interface),如下所示:
SELECT name,value from foo where name IN ('bar', 'other_bar') LIMIT 2;
在那个查询之后,我想要一个我可以去的散列:
foo[:bar] # output: value1
foo[:other_bar] # output: value2
使用 ActiveRecord 收集对象并将它们分组以便我可以使用上面的界面的最佳方法是什么?
最佳答案
在 Rails 2 中
foos = Foo.all :select => "name, value",
:conditions => ["name in (?)", %w(bar other_bar)],
:limit => 2
在 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 中
foo = foos.each_with_object({}) { |f, hash| hash[f.name.to_sym] = f.value }
关于ruby-on-rails - Ruby:将一组 ActiveRecord 对象分组到散列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5490582/