Tyler DeWitt
Tyler DeWitt

Reputation: 23576

Rails ActiveRecord Query for Not Equal

Rails 3.2.1

Is there a way (without squeel) to use the hash syntax of ActiveRecord to construct a != operator?

Something like Product.where(id: !params[:id])

Generates SELECT products.* FROM products WHERE id != 5

Looking for the opposite of Product.where(id: params[:id])

UPDATE

In rails 4 there is a not operator.

Product.where.not(id: params[:id])

Upvotes: 67

Views: 52864

Answers (4)

Dan McClain
Dan McClain

Reputation: 11920

You can use the following

Product.where('id != ?', params[:id])

Which will generate what you are looking for, while parameterizing the query.

With Rails 4, the following syntax has been added to support not clauses

Product.where.not(id: params[:id])

Add multiple clauses with chaining...

Product.where.not(id: params[:id]).where.not(category_id: params[:cat_id])

Upvotes: 93

PinnyM
PinnyM

Reputation: 35533

There isn't any built-in way to do this (as of Rails 3.2.13). However, you can easily build a method to help you out:

ActiveRecord::Base.class_eval do
  def self.where_not(opts)
    params = []        
    sql = opts.map{|k, v| params << v; "#{quoted_table_name}.#{quote_column_name k} != ?"}.join(' AND ')
    where(sql, *params)
  end
end

And then you can do:

Product.where_not(id: params[:id])

UPDATE

As @DanMclain answered - this is already done for you in Rails 4 (using where.not(...)).

Upvotes: 34

boulder_ruby
boulder_ruby

Reputation: 39695

Rails 4 has this figured out. So maybe you could just update your rails app

Model.where.not(:id => params[:id])

Upvotes: 24

Viren
Viren

Reputation: 5962

Arel could the one you might want to explore It is included in Rails 3+ I guess

Here How you do it using Arel

Product.where(Product.arel_table[:id].not_eq(params[:id]))

and

Product.where(Product.arel_table[:id].not_eq(params[:id])).to_sql 

would generate SQL Like below

SELECT `products`.* FROM `products`  WHERE (`products`.`id` != 1)

Hope this Help

Upvotes: 14

Related Questions