Ruby-on-rails Rails ActiveRecord 查询不相等

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12184816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:42:16  来源:igfitidea点击:

Rails ActiveRecord Query for Not Equal

ruby-on-railsactiverecord

提问by Tyler DeWitt

Rails 3.2.1

导轨 3.2.1

Is there a way (without squeel) to use the hash syntax of ActiveRecord to construct a !=operator?

有没有办法(没有squeel)使用 ActiveRecord 的哈希语法来构造!=运算符?

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

就像是 Product.where(id: !params[:id])

Generates SELECT products.* FROM products WHERE id != 5

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

Looking for the opposite of Product.where(id: params[:id])

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

UPDATE

更新

In rails 4 there is a notoperator.

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

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

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

采纳答案by PinnyM

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:

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

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

正如@DanMclain 回答的那样 - 这已经在 Rails 4 中为您完成(使用where.not(...))。

回答by Dan McClain

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

在 Rails 4 中,添加了以下语法以支持 not 子句

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

Add multiple clauses with chaining...

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

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

回答by boulder_ruby

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

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

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

回答by Viren

Arelcould the one you might want to explore It is included in Rails 3+ I guess

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

Here How you do it using Arel

这里如何使用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

将生成如下 SQL

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

Hope this Help

希望这有帮助