【发布时间】:2011-06-02 15:43:45
【问题描述】:
我想执行一个 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 可能在正确的轨道上,但我还没有成功适应它。任何帮助将不胜感激。
【问题讨论】:
-
你试过
:conditions => [ "id not IN (?)", ids_to_exclude ]吗?注意括号而不是大括号。 -
在 Rails 3.2.1 中,我最近在查询中使用了这个
MyModel.order('created_at DESC').where('id NOT in (?)', ids_to_exclude).limit(5)
标签: activerecord ruby-on-rails-3 arel active-relation