Rails ActiveRecord查询不相等



Rails 3.2.1

有没有一种方法(不使用scroll)可以使用ActiveRecord的哈希语法来构造!=运算符?

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

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

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

更新

在导轨4中有一个not操作员。

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

您可以使用以下

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

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

在Rails4中,添加了以下语法来支持not子句

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

添加多个带链接的子句。。。

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

没有任何内置的方法可以做到这一点(从Rails 3.2.13开始)。但是,您可以轻松地构建一个方法来帮助您:

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

更新

正如@DanMclain所回答的那样——这已经在Rails4中为您完成了(使用where.not(...))。

Rails 4已经解决了这个问题。所以也许你可以更新你的rails应用程序

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

Arel可能是您想要探索的一个,它包含在Rails3+中,我想是

这里介绍如何使用Arel

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

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

会在下生成类似SQL

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

希望这能帮助

最新更新