3

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?

4 Answers 4

15

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 }
Sign up to request clarification or add additional context in comments.

Comments

4

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] }]

3 Comments

Note that this will only work for Ruby 1.9; for Ruby 1.8 you must use Hash[ *foo.flatten ].
@rubyprince is right, I tested this in a script/console running 1.8.7.
My mistake, I should have said 1.8.6; Ruby 1.8.7 is such a bizarre beast.
1
Hash[result.map { |r| [r[:name].to_sym, r[:value]] } ]

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.