views:

67

answers:

2

I have a table with MANY rows, I need just the IDs of certain rows. The slow way is to call

SomeARClass.find(:all, :conditions => {:foo => true}, :select => :id)

This returns AR Objects...

Is there a way to call a select on a class and have it return a plain old ruby data structure. Something like this:

SomeARClass.select(:id, :conditions => {:foo => true})
-> [1,2,3]
A: 

I don't think there is anything like SomeARClass.select(:id, :conditions => {:foo => true}) but you have two options

  1. SomeARClass.find(:all, :conditions => {:foo => true}, :select => :id).map(&:id)
    #=> [1,2,3,4]
    
  2. id_hash = ActiveRecord::Base.connection.select_all('select id from tablename')
    #=>  [{"id"=>"1"}, {"id"=>"2"}, {"id"=>"3"}, {"id"=>"4"}]
    
    
    id_hash.map(&:values).flatten
    #=>  ["1", "2", "3", "4"]
    

The second option returns only a hash and not Active record objects but it does looks a bit hackish.

nas
A: 
ActiveRecord::Base.connection.select_all(sql)

or

SomeARClass.connection.select_all(sql)

This is what you want to use. It returns an array of hashes. It should be used sparingly though. Hand coded sql is what ActiveRecord was built to replace. I only use in in really performance critical areas where constructing and returning AR objects is too slow.

Kevin