Rails Database Best Practices
Efficient and chainable Scopes
- Always return
ActiveRecord::Relation, so scopes remain chainable - Filter and sort in the database (its much quicker)
- Don't order inside the scope (or create a separate scope). So the user can oder as they like
Bad

Good

Reduce Calls to the database
Try to use as much of .includes(), .joins() (see here), .group() (see here)and .having() (see here). Sometimes 
Check this chapter out for more about the topic 13. Eager Loading Associations
Use Indexes
Every column that gets used in a where clause should have an index.
# shell command
bin/rails generate migration AddPartNumberToProducts part_number:string:index
# migration script
class AddPartNumberToProducts < ActiveRecord::Migration[8.0]
def change
add_column :products, :part_number, :string
add_index :products, :part_number
end
end
Avoid 'ad-hoc' queries
Only ever use ad-hoc queries inside scopes or query objects. This allows for better testing and enables to reuse it.
Use the Right Types
Use the types the RDBMS gives you. Not just the ORM ones. Some of them require an extension.