Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4, raw query using ActiveRecord

Is there currently a way to do a raw SQL select query using ActiveRecord in Rails 4.0.0.beta1? I see ActiveRecord::Base.execute no longer exists. What's the correct way of going about this?

like image 779
randombits Avatar asked Apr 06 '13 20:04

randombits


3 Answers

Here try this, select example.. :

query = "select ...."
results = ActiveRecord::Base.connection.execute(query)
like image 188
ant Avatar answered Oct 19 '22 16:10

ant


Just to add my ten pence, a raw query using Model.connection.execute won't return an ActiveRecord model - it'll return a raw data set.

The following will return ActiveRecord models:

MyModel.find_by_sql(query)

edit: assuming of course that you're running a select.

like image 30
Guillaume Roderick Avatar answered Oct 19 '22 16:10

Guillaume Roderick


In Rails 4 (perhaps previous versions as well), if you're going with a custom query for speed, you can add a :skip_logging argument to avoid writing to the log:

query = "SELECT ..."
results = MyModel.connection.execute(query, :skip_logging)

(Note: If I'm reading the sources correctly, this might not hold true in PostgreSQL.)

like image 10
fearless_fool Avatar answered Oct 19 '22 17:10

fearless_fool