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

Disable auto-incremental field in Rails Migrations

Posted by Dan Sosedoff on August 12, 2010

Since i`ve been using both DataMapper (Merb/Sinatra) and ActiveRecord (Rails) a lot i noticed that AR acts weight when i manually set PK key, particularly ID field, which you dont have to define by default. In DM you have to define it as ‘Serial’.

So, the task is to create/update records in your database which is supposes to represent data from primary database. In such cases all ID`s should be unique and equal to each other.

To disable autoincremental ID field in your AR models just use this option:

create_table :foo, :id => false do |t|
  t.integer   :id, :options => 'PRIMARY KEY'
  # .... rest of columns
end