Pages

Tuesday, January 7, 2014

Not Equal support for Active Record queries in Rails 4

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 awhere 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'))

No comments:

Post a Comment