ntonnelier ntonnelier - 9 months ago 33
SQL Question

Difference between ActiveRecord::Base.connection and find_by_sql

I need to perform some custom queries on my rails application and was wondering wich approach is better:

results = ActiveRecord::Base.connection.execute(query)



Been reading the documentation but didn't really get how they perform.


execute is a low level method. It returns whatever the database driver returns, for example an instance of Mysql2::Result. You can execute any sort of query with this

find_by_sql returns an array of ActiveRecord objects of the appropriate class, constructed from the results (so it wouldn't make sense to pass a query that doesn't produce a suitable result set).

A halfway house are methods on connection such as select_all, select_values etc. These don't create active record objects, but do transform the raw driver results into arrays, hashes, strings etc.