Use database sorting and filtering whenever possible in Rails

The select function is my go to function whenever I want Rails to filter an array of hashes. This is pretty common in helpers.

def users_filtered_by_status(users, status) { |u| u.status.downcase == status.downcase }

However, we must always keep in mind and remember that Ruby is slow and the database is pretty fast with select and filtering.

Even if you are using a helper, always ask yourself, could this be done in the database? If users is an ActiveRecord relation, that means it’s going to be lazy evaluated when we actually access it. We need to change this to a where instead of a select on the array to make the database do the sorting and filtering.

So the new method should look like this:

def users_filtered_by_status(users, status)
  users.where(status: status)

Since it uses, the where function. It will be lazy evaluated. And since it uses the database to do the sorting and filtering, it would be pretty efficient compared to the select method.