Active Record where tricks - Rails Tricks Issue 5
Hey, this week, I am bringing you Active Record tricks to find records with missing associations or with associated records only, and to negate your conditions.
The first three methods I will cover are all implemented in ActiveRecord::QueryMethods::WhereChain, which acts as a placeholder object for where
queries with no direct parameter.
The first method is associated
, which generates an inner join SQL query with a NOT NULL condition on the join field. For instance, if you want to find all blog posts in your database with an author, you can achieve it with the following code:
The next method is missing
, which does the opposite and returns the records with missing associations:
It is worth nothing that you can specify multiple associations to both methods, so if you would want to find all posts where the author is missing and has zero comments, you can do so by calling Post.where.missing(:author, :comments)
or if you want to find all posts where the author is set and has at least one comment, you can call Post.where.associated(:author, :comments)
.
The third method I want to mention is not
, which can be used to negate a where
condition:
There is also the not so well-known invert_where
method, which inverts the previous where condition. So you can do this:
You can also use it when you define scopes to not duplicate your conditions:
That’s it for this week!