Tips and tricks

Tips and Tricks

ActiveRecord

Generic warnings

ActiveRecord is a very powerful component of rails. That's an abstraction between our models and the database, which allows to achieve many things.

But sometimes, that comes at the cost of the performance. Ruby is good for many things, but manipulating a lot of data in Ruby can be sometimes very inefficient due to the cost of the memory that we use.

So, when using ActiveRecord, let's think about the produced SQL statements and think if we could not optimize ActiveRecord usage by offloading some part of the work to the database.

For instance:

# Don't do 
Account.last(10).map(&:name) 
# It produces SELECT * FROM accounts ; Then it selects the name

# Do 
Account.last(10).pluck(:name) 
# It produces SELECT name FROM accounts ; So it fetches less data

# Don't do 
Account.last(10).group_by(&:country).map do |k, v| [k, v.count] end
# It produces SELECT * FROM accounts ; Then it groups
  
# Do 
Account.last(10).group(:country).count.to_a 
# It produces SELECT company, count(*) FROM accounts GROUP BY country 
# so, this lets the database making the work  

N+1 request

One big performance killer of rails is the N+1 request. N+1 can occur in scenarios as the following:

In that case, we can see in the database that the queries produced are:

That's because we're asking the name of the account's admin, which is loaded, as with the account's admin while trying to access that value.

Instead, it's better to pre-fetch all the data, using one of the following techniques:

Reset columns information in a migration

reset_column_information is a useful method when just after creating a table or a column in a migration, you want to populate it with some default values.

Without it, the following migration will throw an error on line 7 stating that is_happy does not exist on the table employees:

Rails Migration

Interesting article on Zero Downtime

Read this article to better understand steps you can put in place to ensure that you rails migration are not locking the DB in production.

https://medium.com/klaxit-techblog/zero-downtime-migrations-with-activerecord-47528abe5136

Rails console

Using reload!

When interacting into the rails console, using reload! will reflect changes made into the code immediately, without the need to quit and re-open console.

Last updated

Was this helpful?