如何从 Rails 中的查询中排除一组 id(使用 ActiveRecord)? [英] How to exclude an array of ids from query in Rails (using ActiveRecord)?

查看:15
本文介绍了如何从 Rails 中的查询中排除一组 id(使用 ActiveRecord)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行一个 ActiveRecord 查询,该查询返回除具有特定 ID 的那些记录之外的所有记录.我想排除的 id 存储在一个数组中.所以:

I would like to perform an ActiveRecord query that returns all records except those records that have certain ids. The ids I would like excluded are stored in an array. So:

ids_to_exclude = [1,2,3]
array_without_excluded_ids = Item. ???

我不知道如何完成第二行.

I'm not sure how to complete the second line.

背景:我已经尝试过的:

我不确定背景是否必要,但我已经尝试了 .find 和 .where 的各种组合.例如:

I'm not sure background is necessary, but I've already tried various combinations of .find and .where. For example:

array_without_excluded_ids = Item.find(:all, :conditions => { "id not IN (?)", ids_to_exclude })
array_without_excluded_ids = Item.where( "items.id not IN ?", ids_to_exclude)

这些都失败了.这个提示可能是正确的,但我有没有成功地适应它.任何帮助将不胜感激.

These fail. This tip might be on the right track, but I have not succeeded in adapting it. Any help would be greatly appreciated.

推荐答案

这应该有效:

ids_to_exclude = [1,2,3]
items_table = Arel::Table.new(:items)

array_without_excluded_ids = Item.where(items_table[:id].not_in ids_to_exclude)

而且它完全面向对象,没有字符串:-)

And it's fully object-oriented with no strings :-)

这篇关于如何从 Rails 中的查询中排除一组 id(使用 ActiveRecord)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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