views:

41

answers:

3

Hi I would like to ask if its possible get array with clear data from ActiveRecord query without using map, collect or each.

names = User.find(:all, :select => "name")
return names == [#<User name:"Peter">,#<User name:"Martin">]

and I want names == ["Peter", "Martin"] without using map, collect or each. Thanks for your answers.

A: 

No you can't do that w/o using map, collect each ... etc......

In otherwords you can't get result like this in a single query.

Salil
+1  A: 

Even if ActiveRecord provided a method to do what you want (single column to array of values), it would internally use a loop (each or collect) to do it.

I don't see what is so wrong with using a loop in this case, Ruby makes it quite easy to do it.

users = User.find(:all, :select => "name").collect { |u| u.name }
Samuel
i think question clearly mentioned "without using map, collect or each"
Salil
Yes but it not possible to do it without looping. So I offered the most succinct solution possible.
Samuel
A: 
User.connection.select_values("SELECT name FROM users")
#=> ["francois"]
François Beausoleil
I stand corrected that ActiveRecord doesn't provide such a method. But it does use map internally as I said.
Samuel
wow... :) interesting method it is from activerecord?
Suborx
Yes it is in ActiveRecord in rails 2. http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#M001421
Samuel