Ruby on rails Rails3:如何获取所有ID不在给定列表中的帖子?

Ruby on rails Rails3:如何获取所有ID不在给定列表中的帖子?,ruby-on-rails,ruby-on-rails-3,activerecord,active-relation,Ruby On Rails,Ruby On Rails 3,Activerecord,Active Relation,要获取所有发布者id为10、16或17的帖子,我需要: Post.where(:publisher_id => [10, 16, 17]) 我如何获得所有发布者id不等于10、16或17的帖子(即除这三个id之外的所有可能id)?未经测试,但应该类似(使用metawhere gem): 只需执行以下操作: Post.where(["publisher_id NOT IN (?)", [10, 16, 17]]) 使用带有Arel的“纯”ActiveRecord语法,使用Rails 3,

要获取所有发布者id为10、16或17的帖子,我需要:

Post.where(:publisher_id => [10, 16, 17])

我如何获得所有发布者id不等于10、16或17的帖子(即除这三个id之外的所有可能id)?

未经测试,但应该类似(使用metawhere gem):

只需执行以下操作:

Post.where(["publisher_id NOT IN (?)", [10, 16, 17]])
使用带有Arel的“纯”ActiveRecord语法,使用Rails 3,您可以执行如下操作:

Post.where( Post.arel_table[:publisher_id].not_in([10, 16, 17]) )

此页上的每个答案都是错误的,因为这些答案都不考虑所有数组情况,尤其是只有一个元素的数组

下面是一个使用本页上的任何“所谓”解决方案将失败的示例:

@ids = [1]
Post.where("publisher_id NOT IN (?)", @ids)
#ERROR
Post.where("publisher_id NOT IN (?)", [4])
#ERROR
#...etc

#ALSO
@ids = []
Post.where("publisher_id NOT IN (?)", @ids)
#ERROR
Post.where("publisher_id NOT IN (?)", [])
#ERROR
#...etc

#The problem here is that when the array only has one item, only that element is 
#returned, NOT an array, like we had specified

#Part of the sql that is generated looks like:
#...WHERE (publisher_id NOT IN 166)

#It should be:
#...WHERE (publisher_id NOT IN (166))
本页上唯一正确的答案是@Tudor Constantin's。但问题是,他并没有真正展示出一种使用他的方法来解决OP发布的真实抽象示例问题的“方法”(不仅仅是使用硬编码的数字)

下面是我的解决方案,它动态查找不在Activerecord关联中的ID,给定要排除的ID数组,该数组将使用n个元素的数组(…包括n=1和n=0)


如果这对你有帮助,请投票!如果您对我的评论感到困惑或不理解,请告诉我。

我使用的简洁解决方案:

ids = #however you get the IDS
Post.where(["id not in (?)", [0,*ids])
  • 0的存在意味着它在中始终有一个元素(假设没有任何元素的ID为0)
  • ID成为splat意味着它将始终是一个数组

在rails 4中,我们可以执行以下操作

Post.where.not(:publisher_id => [10, 16, 17])
SELECT "posts".* FROM "posts"  WHERE ("posts"."publisher_id" NOT IN (10, 16, 17))
它将生成如下所示的SQL

Post.where.not(:publisher_id => [10, 16, 17])
SELECT "posts".* FROM "posts"  WHERE ("posts"."publisher_id" NOT IN (10, 16, 17))

我不确定为什么需要额外的
[]
。这很好:
Post.where(“publisher\u id不在(?),[10,16,17])
。谢谢这只是Rails 2以前语法中的一个老习惯:conditions选项;)不客气。
SELECT "posts".* FROM "posts"  WHERE ("posts"."publisher_id" NOT IN (10, 16, 17))