ntonnelier
ntonnelier

Reputation: 1549

Difference between ActiveRecord::Base.connection and find_by_sql

I need to perform some custom queries on my rails application and was wondering which 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.

Upvotes: 1

Views: 1288

Answers (1)

Frederick Cheung
Frederick Cheung

Reputation: 84114

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.

Upvotes: 5

Related Questions