[英]Ruby: group an array of ActiveRecord objects in a hash
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: 我想将一个ActiveRecord对象数组分组到一个哈希中,该哈希的接口在查看如下所示的SQL语句之后很容易查询:
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
What's the best way to collect the objects with ActiveRecord and group them so I can use the interface above? 使用ActiveRecord收集对象的最佳方法是什么,并将它们分组,以便我可以使用上面的界面?
In Rails 2 在Rails 2中
foos = Foo.all :select => "name, value",
:conditions => ["name in (?)", %w(bar other_bar)],
:limit => 2
In Rails 3 在Rails 3中
foos = Foo.where("name in (?)", %w(bar other_bar)).select("name, value").limit(2)
Then 然后
foo = Hash[foos.map { |f| [f.name.to_sym, f.value] }]
or 要么
foo = foos.inject({}) { |h, f| h[f.name.to_sym] = f.value; h }
or in Ruby 1.9 或者在Ruby 1.9中
foo = foos.each_with_object({}) { |f, hash| hash[f.name.to_sym] = f.value }
如果我理解正确的话:
foo = Hash[Foo.find(:all, :limit => 2, :select => "name, value", :conditions => ["name in ('bar', 'other_bar')"]).map { |s| [s.name.intern, s.value] }]
Hash[result.map { |r| [r[:name].to_sym, r[:value]] } ]
models.inject({}) {|h,m| h[ m.name.to_sym ] = m.value; h }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.