Rails:使用named_scope触发MySQL“in”
问题:
我想运行一个查询,该查询会触发诸如
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])
PROBLEM:
I want to run a query which would trigger something like
select * from users where code in (1,2,4);
using a named_scope
.
WHAT I TRIED:
This is for a single code:
named_scope :of_code, lambda {|code| {:conditions => ["code = ?", code]}}
I tried something like
named_scope :of_codes, lambda {|codes| {:conditions => ["code in ?", codes]}}
and sent
user.of_codes('(1,2,4)')
it triggersselect * from users where code in '(1,2,4)'
which raises a MySQL error because of the extra quotes.
PS: Ideally I would like to send user.of_codes([1,2,4])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这将起作用,只是找到而不会让您遭受 SQL 注入攻击:
如果您想要更狡猾一点,您可以这样做:
然后您可以使用
Array
来调用它(如上所述) :User.of_codes([1, 2, 3])
,或使用代码参数列表:User.of_codes(1, 2, 3)
。This will work just find and not expose you to the SQL injection attack:
If you want to be a little more slick, you can do this:
Then you can call it either with an
Array
(as above):User.of_codes([1, 2, 3])
, or with a list of code arguments:User.of_codes(1, 2, 3)
.最简单的方法是使用散列作为条件而不是数组:
这将按预期工作。
The simplest approach would be to use a hash for conditions instead of an array:
This will work as expected.
您可以尝试以下
并
编辑 SQL INJECTION PROBLEM USE
和
you can try follwing
and
EDITED For SQL INJECTION PROBLEM USE
and