Custom Software and Offshore Development | LARION

Rails Database Best Practices

Working on an oldish Rails project, I came across some smelly ActiveRecord code that begged for some refactoring love. I also spent some time speeding up pages with slow/many database calls. Between those two experiences, I felt the inspiration to write-up some “Back to Basics” Rails Database Best Practices.

Rule #1: Let your Database do its Job
Rule #2: Write efficient and chainable Scopes
Rule #3: Reduce calls to the Database
Rule #4: Use Indexes
Rule #5: Use Query Objects for complicated Queries
Rule #6: Avoid ad-hoc queries outside of Scopes and Query Objects
Rule #7: Use the Right Types
Rule #8: Consider your database’s Full-Text Search
Rule #9: Use stored procedures as a Last Resort

Wrapping up…
I believe a product will perform better and be easier to work with when the database is used to its potential.

Reducing the number of queries, using indexes, or any of the other suggestions aren’t premature optimizations IMHO. It’s using your database correctly. Of course, there is a point of diminishing returns: e.g. writing a tortuous raw SQL query to go from 3 easy queries down to 1. Use your best judgement.

 

Related Articles:
http://blog.carbonfive.com/2016/11/16/rails-database-best-practices/

 

 

More interesting resources

10 Reasons to Choose Offshore Software Development_LARION