@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))
@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!
7条答案
按热度按时间r1wp621o1#
只需执行以下操作:
qgelzfjb2#
在rails 4中,我们可以像下面这样做
它将生成如下SQL
eit6fx6z3#
未经测试,但应该像(使用metahere gem):
vm0i2vca4#
使用“纯”ActiveRecord语法,并在Rails 3中使用Arel,您可以执行以下操作:
vcirk6k65#
我用过的最好的解决方案:
2ekbmq326#
这一页上的每一个答案都是错误的,因为这些答案都没有考虑到所有数组的情况,特别是只有一个元素的数组。
下面是一个使用本页上任何“所谓”解决方案都将失败的示例:
在这个页面上唯一的答案,实际上是在正确的轨道上,并照顾这个非常重要的情况是@都铎康斯坦丁的。但问题是,他实际上并没有展示一种“方法”,用他的方法来解决OP发布的真实的抽象的示例问题(而不仅仅是使用硬编码的数字)。
下面是我的解决方案,动态查找不在Activerecord关联中的id,给定一个要排除的id数组,它将适用于n个元素的数组(...包括n=1和n=0)
vmpqdwk37#