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.
Comments
thanks. very useful pointer.
there are nicer ways than execute, btw: you can use any of the other connection methods. This is how I get a list of matching tags for an ajax autocompleter:
Tag.connection.select_values(“SELECT name FROM #{Tag.table_name} where account_id = #{current_account.id} and name like ‘#{params[:stem]}%’”)
Nasty, but efficient. More possibilities at http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html
best,
will