Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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])

like image 632
Tyler DeWitt Avatar asked Aug 29 '12 19:08

Tyler DeWitt


2 Answers

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]) 
like image 135
Dan McClain Avatar answered Sep 17 '22 16:09

Dan McClain


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(...)).

like image 35
PinnyM Avatar answered Sep 19 '22 16:09

PinnyM