gpt4 book ai didi

activerecord - Rails where not equals *any* 值数组

转载 作者:行者123 更新时间:2023-12-04 02:41:03 25 4
gpt4 key购买 nike

我试过这样的事情

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

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

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

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

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

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

最佳答案

您的第一段代码不起作用,因为 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 与您的数组中的任何元素匹配的记录之外的所有记录。

关于activerecord - Rails where not equals *any* 值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19940418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com