As Rails developers, we’re constantly using ActiveRecord, but are mostly using the same subset of methods and features it provides. Some of its lesser known and lesser used features could help you write cleaner code in the future and delight your co-workers. So let’s dive right in!
Instead of calling
map on ActiveRecord objects, use
pluck if you only need a list of attributes. It avoids building ActiveRecord model objects and is a lot more efficient for larger collections.
You can provide an array argument for the
where clause, which is translated to an SQL
Where and Not
where.not will test for inequality, where you might have used
where('category != ?', 'rails') in the past. This was introduced with Rails 4.0.
Where clauses also support ranges. In the example above we see a ruby date range that gets elegantly translated
Instead of the using the
order argument with a string as
order("published_on DESC"), you can simply pass a hash.
Discarding From The Chain
expect syntax you can get rid of clauses to the ActiveRecord relation that were added before. This could
come in handy if you’re given a base scope that is valid for all cases except yours and avoids throwing away any other modifications to the relation.
The Null Relation
This feature might look like non-sense at first. The
none clause makes sure that whatever clause is added to the relation, the result will always be empty. Again, this might make sense if you are provided with a relation and have to return one again. Say now we have a case where the current query is not valid due to permission constraints. Adding the
none clause makes sure that whatever relation modification follows, the final query will not hit the database and will be empty.
readonly clause makes sure that a relation cannot be modified. This might make sense if you pass an object to any code that is not yours (e.g. a library) and want to make sure that the object is not modified.
So that’s it. I hope you can use some of these tricks to not only make your code faster and more elegant, but also more readable.