23

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

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

我不确定如何完成第二行。

背景:我已经尝试过的:

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

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)

这些都失败了。 这个技巧可能在正确的轨道上,但我没有成功地适应它。任何帮助将不胜感激。

4

4 回答 4

37

Rails 4 解决方案:

ids_to_exclude = [1,2,3]
array_without_excluded_ids = Item.where.not(id: ids_to_exclude)
于 2013-11-14T17:15:24.977 回答
32

这应该有效:

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)

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

于 2011-01-03T01:09:50.487 回答
2

您也可以使用Squeelgem 来完成这样的查询。它的文档,在这里

于 2013-02-19T11:03:37.580 回答
2

正如 nslocum 所写,以下内容运行良好:

Item.where.not(id: ids_to_exclude)

如果您的“要排除的 ID”来自查询(此处带有示例条件),您甚至可以更进一步:

Item.where.not(id: Item.where(condition: true))

如果您需要过滤另一个模型,这很有用:

OtherModel.where.not(item_id: Item.where(condition: true))
于 2020-06-24T07:00:09.890 回答