activerecord - 如何从 Rails 的查询中排除 id 数组(使用 ActiveRecord)?

标签 activerecord ruby-on-rails-3 arel active-relation

我想执行一个 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/

相关文章:

ruby-on-rails - 无法获取对象属性

ruby-on-rails-3 - 我在哪里可以找到好的 AREL 文档?

sql - 使用 Date.today 加入命名范围的一部分

sql - 使用 JOIN 和 LIKE 的 Rails OR 查询

ruby-on-rails - has_many在Rails中进行关联迁移

ruby-on-rails-3 - 在 Rails 3 查询中使用 count() 和 group(),还是只使用 sql?

c# - 使用 CaSTLe ActiveRecord 从表中查找前 10 个结果

ruby-on-rails - has_many :though (undefined method class_name for nil:NilClass) 的 NoMethodError

ruby-on-rails - Net::SSH 从生产 rails 控制台工作,从生产 webapp 工作 AuthenticationFailed

ruby-on-rails - Rails 3 数据建模帮助 - 具有许多、属于、嵌套属性