ActiveRecord的用户提供的列名 [英] ActiveRecord user-supplied column name
问题描述
我想允许的Rails应用程序的最终用户基于任意列的值来限制的结果。简单地说,我想要做的事大致相当于:
I am trying to allow the end-user of a rails app to limit results based on the value of an arbitrary column. At its simplest, I want to do something roughly equivalent to:
"SELECT * FROM products WHERE (#{params[:min_col]} >= #{params[:min]})"
没有注入漏洞。
without the injection vulnerability.
例如, example.com/myapp/catalog?min_col=sell_price&min=300
将返回所有产品sell_price大于或等于$ 3.00
For example, example.com/myapp/catalog?min_col=sell_price&min=300
would return all products with sell_price greater than or equal to $3.00
我尝试添加一个范围,这样的模式:
I tried adding a scope like this to the model:
->(column,min) { where("? >= ?", column, min) }
和传递的URI参数的范围,但是这种收益率
and passing the uri parameters to that scope, but this yields
WHERE ('sell_price' >= '300')
这似乎只是比较两个文本字符串 - 此查询和其他类似总是返回的每一行或没有行。如何获得比较反对 PARAMS
?
推荐答案
要prevent SQL注入,您应该验证列是一个有效的
To prevent sql injection, you should validate the column is a valid one
valid_cols = ["c1", "c2"]
valid_cols.include?(column) or raise "Bad query"
然后,你可以使用查询界面和以前一样
Then you can just use the query interface as before
Model.where("#{column} >= ?", min)
这篇关于ActiveRecord的用户提供的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!