randombits
randombits

Reputation: 48440

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:

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?

Upvotes: 3

Views: 6851

Answers (4)

rubyprince
rubyprince

Reputation: 17793

In Rails 2

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

In 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

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

Upvotes: 15

scragz
scragz

Reputation: 6690

models.inject({}) {|h,m| h[ m.name.to_sym ] = m.value; h }

Upvotes: 0

Pablo B.
Pablo B.

Reputation: 1833

Hash[result.map { |r| [r[:name].to_sym, r[:value]] } ]

Upvotes: 1

Michael Kohl
Michael Kohl

Reputation: 66837

If I understood you correctly:

foo = Hash[Foo.find(:all, :limit => 2, :select => "name, value", :conditions => ["name in ('bar', 'other_bar')"]).map { |s| [s.name.intern, s.value] }]

Upvotes: 4

Related Questions