ntonnelier ntonnelier - 5 months ago 14
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)


Or

Model.find_by_sql(query)


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

Answer

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.

Comments