Custom SQL queries in Rails

Posted by Dan Sosedoff on August 17, 2010

Sometimes ORM just cant hand some complicated query, especially when the results of such query does not refer to any table.

For Rails ActiveRecord:

class Item < ActiveRecord::Base
   def self.some_heavy_stuff(param)
     sql = self.sanitize_sql(['.... SQL ....', param)
     self.connection.execute(sql)
   end
end
 
# usage
data = Item.some_heavy_stuff(1)
data.each do |row|
   puts row['id']
end

For DataMapper its almost the same (they`ve replaced query method with select not a long time ago):

class Item
  include DataMapper::Resource
 
  property :id, Serial
  property :foo, String
  property :bar, String
 
  def self.some_heavy_stuff(param)
     repository(:default).adapter.select('... SQL ...')
  end
end
Trackbacks

Trackbacks are closed.

Comments

Comments are closed.