2

问题:

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

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])

4

3 回答 3

4

这只会找到而不会让您暴露于 SQL 注入攻击:

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)

于 2010-06-30T11:59:23.773 回答
3

最简单的方法是对条件使用哈希而不是数组:

named_scope :of_codes, lambda { |*codes| { :conditions => { :code => codes } } }

这将按预期工作。

User.of_codes(1, 2, 3) # => SELECT ... code IN (1,2,3)
User.of_codes(1) # => SELECT ... code IN (1)
于 2010-06-30T22:21:25.723 回答
2

你可以尝试以下

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

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

为 SQL 注入问题使用而编辑

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

user.of_codes([1,2,4])
于 2010-06-30T10:55:07.733 回答