Not Equal support for Active Record queries [Rails 4 Countdown to 2013]

Posted on

This post is part of a series of 31 Rails 4 articles being released each day in December 2012.

The Active Record query interface for the most part abstracts SQL from the developer. However, there is a condition that always requires using pure string conditions in a where clause: <> or !=, depending on the database. Starting in Rails 4, query method not has been added to rectify this.

Example

Let's look at an example of executing the new not query method. First we will look at how it was done in Rails 3, and then look at how Rails 4 handles the same problem. All examples will be querying against an Article model with a title field. The examples below will be using a SQLite database.

The Rails 3 Way

Article.where("title != ?", params[:title])

The Rails 4 Way

To use the new query method, it must be chained to a where clause with no arguments:

Article.where.not(title: 'Rails 3')
# >> SELECT "articles".* FROM "articles" WHERE ("articles"."title" != 'Rails 3')

The not query method can also accept an array to ensure multiple values are not in a field:

Article.where.not(title: ['Rails 3', 'Rails 5'])
# >> SELECT "articles".* FROM "articles" WHERE ("articles"."title" NOT IN ('Rails 3', 'Rails 5'))

Further Reading

002

This post is by Kevin Faustino. Kevin is the Chief Craftsman of Remarkable Labs and also the founder of the Toronto Ruby Brigade.


Comments

comments powered by Disqus