Rails ActiveRecord query for unequal

Rails 3.2.1

Is there a way (without squeel ) to use the ActiveRecord hash syntax to build the != Operator?

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

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

+48
ruby-on-rails activerecord
Aug 29 '12 at 19:01
source share
4 answers

There is no built-in way to do this (with Rails 3.2.13). However, you can easily create a method that helps you:

 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 replied, this has already been done for you in Rails 4 (using where.not(...) ).

+28
Aug 29 '12 at 19:16
source share

You can use the following

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

What will generate what you are looking for while query parameterization.

The following syntax has been added with Rails 4 to support no offers.

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

Add a few sentences with the chain ...

 Product.where.not(id: params[:id]).where.not(category_id: params[:cat_id]) 
+70
Aug 29 '12 at 19:16
source share

Rails 4 found out. So maybe you can just upgrade the rails app.

 Model.where.not(:id => params[:id]) 
+23
Sep 06 '13 at 7:34 on
source share

Arel may be the one you might want to explore. It is included in Rails 3+, I think

Here How You Do It Using Areli

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

and

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

will generate SQL like below

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

Hope for this help

+13
Aug 30 '12 at 17:08
source share



All Articles