Rails ActiveRecord查询不等于

Tyl*_*itt 60 activerecord ruby-on-rails

Rails 3.2.1

有没有办法(没有吱吱声)使用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])

Dan*_*ain 82

您可以使用以下内容

Product.where('id != ?', params[:id])
Run Code Online (Sandbox Code Playgroud)

在参数化查询时,这将生成您要查找的内容.

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

Product.where.not(id: params[:id])
Run Code Online (Sandbox Code Playgroud)

使用链接添加多个子句...

Product.where.not(id: params[:id]).where.not(category_id: params[:cat_id])
Run Code Online (Sandbox Code Playgroud)

  • 当params [:id]为零时,这可能是无效的.在rails 3.2.XI中使用`Product.where('id!=?',params [:id] .to_i)` (2认同)

Pin*_*nyM 33

没有任何内置方法可以做到这一点(从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
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

Product.where_not(id: params[:id])
Run Code Online (Sandbox Code Playgroud)

UPDATE

正如@DanMclain所回答 - 这已经在Rails 4(使用where.not(...))中为你完成了.


bou*_*uby 24

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

Model.where.not(:id => params[:id])
Run Code Online (Sandbox Code Playgroud)


Vir*_*ren 13

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

这里你是怎么用Arel做的

Product.where(Product.arel_table[:id].not_eq(params[:id]))
Run Code Online (Sandbox Code Playgroud)

Product.where(Product.arel_table[:id].not_eq(params[:id])).to_sql 
Run Code Online (Sandbox Code Playgroud)

将生成SQL如下所示

SELECT `products`.* FROM `products`  WHERE (`products`.`id` != 1)
Run Code Online (Sandbox Code Playgroud)

希望这个帮助

  • @sky_coder将它链接到where(not_eq).where(not_eq) (2认同)