Rails ActiveRecord在join子句中的转义变量

Mar*_*ich 8 mysql sql activerecord ruby-on-rails ruby-on-rails-3

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

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

我怎样才能正确地逃避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)
Run Code Online (Sandbox Code Playgroud)

请注意,这是一个只读数据库,Rails只有有限的参与.我不打算为所有表格设置模型; 我只想进行如上所述的简单查询,而不会让自己暴露于SQL注入攻击.

Mar*_*ich 15

我找到的答案是.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) + ')',
)
Run Code Online (Sandbox Code Playgroud)

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

  • 我以同样的方式实现了这一点 - 似乎ActiveRecord的一个缺点是假设人们不想在连接中添加条件,并以安全的方式这样做! (5认同)