- Return an ActiveRecord::Relation (i.e. don't trigger that query)
- Filter data in the database (not in Ruby)
- Sort in the database (not in Ruby)
- Leave ordering out of scopes (or capture in a dedicated scope)
You can always tack .explain to the end of your ActiveRecord Relation and it will return the database's query plan.
Use the naming convention .data
if it's returning already-queried data, otherwise .relation
Restrict access to ActiveRecord generic query-building methods (e.g. .where
, .group
, .joins
, .not
, etc) to scopes and Query objects.
https://blog.carbonfive.com/2016/11/16/rails-database-best-practices/