我想执行一个 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)
这些失败了。 This tip可能是在正确的轨道上,但我还没有成功地适应它。任何帮助将不胜感激。
最佳答案
Rails 4 解决方案:
ids_to_exclude = [1,2,3]
array_without_excluded_ids = Item.where.not(id: ids_to_exclude)
关于activerecord - 如何从 Rails 的查询中排除 id 数组(使用 ActiveRecord)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4581376/