Rails的ActiveRecord查询不等于

Rails 3.2.1

有没有一种方法(没有squeel )使用ActiveRecord的散列语法来构造!=运算符?

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

生成SELECT products.* FROM products WHERE id != 5

寻找Product.where(id: params[:id])的反义词

UPDATE

在导轨4中not操作员。

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

没有任何内置的方式来做到这一点(如Rails 3.2.13)。 但是,您可以轻松构build一种方法来帮助您:

 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 

然后你可以这样做:

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

UPDATE

正如@DanMclain回答 – 这已经在Rails 4中完成了(使用where.not(...) )。

您可以使用以下内容

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

在参数化查询的同时,它将生成您正在查找的内容。

使用Rails 4,添加了以下语法来支持not子句

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

Rails 4已经搞清楚了。 所以,也许你可以更新你的rails应用程序

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

Arel可能是你可能想要探索的那个,我猜是包含在Rails 3+中的

这里你怎么用Arel来做

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

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

会在下面生成SQL Like

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

希望这个帮助