Rails Database Best Practices


Efficient and chainable Scopes

Bad

Pasted image 20250821110235.png

Good

Pasted image 20250821110328.png

Reduce Calls to the database

Try to use as much of .includes(), .joins() (see here), .group() (see here)and .having() (see here). Sometimes Pasted image 20250821110328.pngthe best way is to write custom SQL.
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.