Skip to content

Instantly share code, notes, and snippets.

@jaimelr
Created September 12, 2019 02:57
Show Gist options
  • Save jaimelr/70bfb08d314ef3823c53f7e2cd97a34a to your computer and use it in GitHub Desktop.
Save jaimelr/70bfb08d314ef3823c53f7e2cd97a34a to your computer and use it in GitHub Desktop.

Rule 1 Let your database do what databases are good at, instead of doing it in Ruby.

Rule 2 Write efficient and chainable Scopes

  1. Return an ActiveRecord::Relation (i.e. don't trigger that query)
  2. Filter data in the database (not in Ruby)
  3. Sort in the database (not in Ruby)
  4. Leave ordering out of scopes (or capture in a dedicated scope)

Rule 3 Reduce calls to the Database

You can always tack .explain to the end of your ActiveRecord Relation and it will return the database's query plan.

Rule 4 Use Query Objects for complicated queries

Use the naming convention .data if it's returning already-queried data, otherwise .relation

Rule 5 Avoid ad-hoc queries outside of Scopes and Query Objects

Restrict access to ActiveRecord generic query-building methods (e.g. .where, .group, .joins, .not, etc) to scopes and Query objects.

Rule 6 Use the right types

Rule 7 Consider your database's Full Text Search

Rule 8 Use Store Procudres as a Last Resort

https://blog.carbonfive.com/2016/11/16/rails-database-best-practices/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment