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])
在参数化查询时,这将生成您要查找的内容.
使用Rails 4,添加了以下语法以支持not子句
Product.where.not(id: params[:id])
使用链接添加多个子句...
Product.where.not(id: params[:id]).where.not(category_id: params[:cat_id])
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
然后你可以这样做:
Product.where_not(id: params[:id])
UPDATE
正如@DanMclain所回答 - 这已经在Rails 4(使用where.not(...))中为你完成了.
bou*_*uby 24
Rails 4解决了这个问题.所以也许你可以更新你的rails应用程序
Model.where.not(:id => params[:id])
Vir*_*ren 13
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如下所示
SELECT `products`.* FROM `products`  WHERE (`products`.`id` != 1)
希望这个帮助
| 归档时间: | 
 | 
| 查看次数: | 40748 次 | 
| 最近记录: |