3

I've tried to do stuff like this

not_allowed = ['5', '6', '7']
sql = not_allowed.map{|n| "col != '#{n}'"}.join(" OR ")
Model.where(sql)

and

not_allowed = ['5', '6', '7']
sql = not_allowed.map{|n| "col <> '#{n}'"}.join(" OR ")
Model.where(sql)

but both of these just return my entire table which isn't accurate.

So I've done this and it works:

shame = values.map{|v| "where.not(:col => '#{v}')"  }.join(".")
eval("Model.#{shame}")

and I'm not even doing this for an actual web application, I'm just using rails for its model stuff. So there aren't any actual security concerns for me. But this is an awful fix and I felt obligated to post this question

4

1 回答 1

4

您的第一段代码不起作用,因为 OR 条件使整个 where 子句始终为真。也就是说,如果 col 的值为 5,则 5 与 5 没有区别,但与 6 和 7 不同,因此,where 子句的计算结果为:false OR true OR true,返回 true。

我认为在这种情况下,您可以改用 NOT IN 子句,如下所示:

not_allowed = ['1','2', '3']
Model.where('col not in (?)', not_allowed)

这将返回所有记录,除了 col 匹配数组中任何元素的记录。

于 2013-11-12T22:12:47.453 回答