写“不在"使用 AREL 的 sql 查询 [英] Writing "not in" sql query using AREL

查看:58
本文介绍了写“不在"使用 AREL 的 sql 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的范围定义如下:

scope :ignore_unavailable, lambda { 
  where([ "Item.id NOT IN (SELECT id FROM Cars WHERE Cars.status = 'NA'" ])
}

目前它使用硬编码的表格名称.如何使用 Arel 等框架改进它?将不胜感激这里的任何帮助.

Currently its using hardcoded tables names. How can I improve it using frameworks like Arel ? Will appreciate any help here.

我在 Rails 3.2 上

I am on Rails 3.2

推荐答案

如果您使用的是 rails 4,一种方法是

If you are using rails 4, one way would be

scope :ignore_unavailable, lambda {
  where.not(id: Car.where(:status => "NA").pluck(:id))
}

对于导轨 3

scope :ignore_unavailable, lambda {
  where("id not in (?)", Car.where(:status => "NA").pluck(:id))
}

这篇关于写“不在"使用 AREL 的 sql 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆