mysql - 连接子句中的 Rails ActiveRecord 转义变量

标签 mysql sql ruby-on-rails ruby-on-rails-3 activerecord

此查询有效,但对 SQL 注入(inject)完全开放:

products = Product.find(pids,
  :select => 'products.*, P.code',
  :joins => "left join product_dist_match P on
    (P.pid = products.pid and P.cid = #{cid})",
)

如何正确转义 cid 变量? conditions 参数允许格式 ['foo = ?', bar] 用于此目的,但 joins 不允许。

我不想使用 find_by_sql,因为那时我需要添加属于模型默认范围的连接和条件(不会是 DRY)。

编辑:我的表结构基本上是这样的:

products: pid (primary key)
product_dist_match: pid, cid, code
customers (not used in the query): cid (primary key)

请注意,这是一个只读数据库,Rails 对它的参与有限。我不打算为所有表格设置模型;我只想执行一个如上所述的简单查询,而不会将自己暴露在 SQL 注入(inject)攻击中。

最佳答案

我找到的答案是在模型上使用.sanitize方法:

products = Product.find(pids,
  :select => 'products.*, P.code',
  :joins => 'left join product_dist_match P on
    (P.pid = products.pid and P.cid = ' + Product.sanitize(cid) + ')',
)

如果您找到更好的解决方案,请发布!

关于mysql - 连接子句中的 Rails ActiveRecord 转义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11831761/

相关文章:

mysql - 查询性能;不确定发生了什么

当有多列连接时,SQL JOIN 限制为前 1

mysql - 使用 concat 按周进行 SQL 分组

ruby-on-rails - 使用 mysql2 Ruby gem 确定 mysql2 服务器版本

ruby-on-rails - 在断言方法的参数中使用感叹号

php - 根据另一个实体字段值查询一个实体

php - Phonegap Android上传到远程数据库失败

php - 检查多个查询中的特定查询是否受到影响

javascript - 删除表单标签中的 novalidate

mysql - 谷歌云 SQL 第二代 : "certificates" is a keyword?