Rails 不等于*任何*值数组

bou*_*uby 3 activerecord

我尝试过做这样的事情

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

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

但这两个都只是返回我的整个表格,这是不准确的。

所以我这样做了并且有效:

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

我什至没有为实际的 Web 应用程序执行此操作,我只是将 Rails 用于其模型内容。所以对我来说没有任何实际的安全问题。但这是一个糟糕的解决方案,我觉得有义务发布这个问题

apa*_*osa 5

您的第一段代码不起作用,因为 OR 条件使整个 where 子句始终为 true。也就是说,如果 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)
Run Code Online (Sandbox Code Playgroud)

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