Rails ActiveRecord Query for Not Equal

Ruby on-RailsActiverecord

Ruby on-Rails Problem Overview


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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

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

Solution 3 - Ruby on-Rails

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

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

Solution 4 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTyler DeWittView Question on Stackoverflow
Solution 1 - Ruby on-RailsDan McClainView Answer on Stackoverflow
Solution 2 - Ruby on-RailsPinnyMView Answer on Stackoverflow
Solution 3 - Ruby on-Railsboulder_rubyView Answer on Stackoverflow
Solution 4 - Ruby on-RailsVirenView Answer on Stackoverflow