Executing raw SQL in Rails.

by Rabbit

Sometimes, when the moon is full, the tides are crashing, and you’re a fucking weirdo, you want to execute raw SQL in Rails. Here’s one way to do it:

ActiveRecord::Base.connection.execute('SELECT * FROM users')
<Mysql::Result:0x32d0994>

I don’t know anything about the MySQL object returned, but that’s how you do it. Have fun.

Update!

Hehe… Since your models extend ActiveRecord::Base, you could simply write…

my_model.connection.execute('...')

Or if you’re inside your model…

class Post
 
  def permalink
    connection.execute('...')
  end
 
end

The Object Thinker in me feels it’s my responsibility to say that executing raw SQL in Rails is a terrible thing and you should never do it. But hey, I understand how it goes… sometimes you just need to get shit done.