How do I get Active Record to exclude items in a query?

Do you know what to do but not how it works?

Ever wanted to understand why Rails views work the way that they do? Why variables from your controllers are visible inside your views?

Sign up below to get a free 5 part email course on how Ruby on Rails view rendering works and gain a deep understanding of the Rails magic.

We will send you the course, plus the occasional update from this web-site. But no spam, we promise, and it's easy to unsubscribe

In SQL I would just write a “not in” query – but what’s the equivalent in ActiveRecord?

By filtering at the database level like this, you can let your database engine do all the optimisation, select the most appropriate index and so on – keeping any performance hits away from your Ruby code.

But what’s the equivalent for your Rails application?

ActiveRecord queries let you pass in an array as a parameter for an “IN” query …

And of course you get all the ActiveRecord parameter sanitising goodness, protecting you from SQL injection attacks (beware the barbarians at the gates).

But for a “NOT IN” query?

Well, in Rails 4 onwards, there’s a nice and easy “not” clause …

Now, go forth and exclude those records …

Do you know what to do but not how it works?

Ever wanted to understand why Rails views work the way that they do? Why variables from your controllers are visible inside your views?

Sign up below to get a free 5 part email course on how Ruby on Rails view rendering works and gain a deep understanding of the Rails magic.

We will send you the course, plus the occasional update from this web-site. But no spam, we promise, and it's easy to unsubscribe