此页面上的每一个答案都是错误的,因为这些答案都不适用所有数组情况,尤其是只有一个元素的数组。
这是一个使用此页面上的任何“所谓”解决方案将失败的示例:
@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 发布的真正抽象示例问题的“方式”(不仅仅是使用硬编码的数字)。
这是我的解决方案,在给定要排除的 id 数组的情况下动态查找不在 Activerecord 关联中的 id,这将与 n 个元素的数组一起使用(...包括 n=1 和 n=0)
@ids = [166]
@attribute = "publisher_id"
@predicate = "NOT IN"
@ids = "(" + @ids.join(",") + ")"
if @ids == "()"
#Empty array, just set @ids, @attribute, and @predicate to nil
@ids = @attribute = @predicate = nil
end
#Finally, make the query
Post.where( [@attribute, @predicate, @ids].join(" ") )
#Part of the sql that is generated looks like:
#...WHERE (publisher_id NOT IN (166))
#CORRECT!
#If we had set @ids = [] (empty array)
#Then the if statement sets everything to nil, and then
#rails removes the blank " " space in the where clause automatically and does
#the query as if all records should be returned, which
#logically makes sense!
如果这对您有帮助,请投票!如果您对我的某个 cmets 感到困惑或不理解,请告诉我。