gpt4 book ai didi

mysql - rails : Using named_scope which triggers a MySQL "in"

转载 作者:数据小太阳 更新时间:2023-10-29 08:19:19 24 4
gpt4 key购买 nike

问题:

我想运行一个会触发类似的查询

select * from users where code in (1,2,4);

使用 named_scope


我尝试了什么:

这是一个单一的代码:

named_scope :of_code, lambda {|code| {:conditions => ["code = ?", code]}}

我试过类似的东西

named_scope :of_codes, lambda {|codes| {:conditions => ["code in ?", codes]}}

并发送

user.of_codes('(1,2,4)')

它会触发select * from users where code in '(1,2,4)' 由于额外的引号引发 MySQL 错误。

PS: 理想情况下我想发送 user.of_codes([1,2,4])

最佳答案

这只会发现而不会让您暴露于 SQL 注入(inject)攻击:

named_scope :of_codes, lambda { |codes|
{ :conditions => ['code in (?)', codes] }
}

User.of_codes([1, 2, 3])
# executes "select * from users where code in (1,2,3)"

如果你想更圆滑一点,可以这样做:

named_scope :of_codes, lambda { |*codes|
{ :conditions => ['code in (?)', [*codes]] }
}

然后您可以使用 Array(如上)调用它:User.of_codes([1, 2, 3]),或使用代码列表参数:User.of_codes(1, 2, 3)

关于mysql - rails : Using named_scope which triggers a MySQL "in",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3148478/

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