SQL

One of the biggest advantages of Active Record is that the developer does not need to write raw SQL queries to perform basic data manipulation in the DB. And like everything in nature, if you don’t use it, you lose it. In that way, we have a bunch of Rails developers that are scared of anything more complex than SELECT * FROM users. That is pretty depressing.

  • Learn SQL and the capabilities of specific databases!
  • If you use Rails, open the console and try to understand what SQL is being generated for each AR query.
  • Do not immediately reach for the “simplest” AR code. That makes a lot of unnecessary queries (N+1 queries, etc.). Think about how the DB will be accessed. Think in SQL!
  • If you use Rails, use the power of AR query composition. That’s fine. You do not need to write raw SQL all the time. But when you need to compose a complex query, and do not know how to do it with AR, write it in SQL first, and then gradually transform it into AR notation.
  • Some queries, especially those using special abilities of the DB (like PARTITION BY, etc.), are better to leave in raw SQL. Think about other developers who will need to support this code. Some things are clearer in AR notation, some are clearer in pure SQL. Just consider the options.

Also, consider that different databases are best suited to different use cases. One web application can make use of multiple databases simultaneously. Think about the type of data you want to operate upon. You can even combine relational DBs (PostgreSQL, MySQL) with document oriented DBs (MongoDB). For graph-like data (“friends of my friends” relations) there is another class of DB, like Neo4J. There are even multiparadigm DBs like ArangoDB.

You should also keep an eye on the DB world. It is changing as fast as web languages and frameworks. It is up to the web developer to propose and use the best data storage solution for the situation, based on the type of data and common query patterns.

To keep productivity high while using special features of specific databases, you can use the Sequel lib. It is very similar to ActiveRecord, but not coupled to Rails, and has a wide selection of plugins and extensions.