简体   繁体   English

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

[英]Rails ActiveRecord escape variable in join clause

This query works, but is totally open to SQL injection: 此查询有效,但对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})",
)

How can I properly escape the cid variable? 我怎样才能正确地逃避cid变量? The conditions parameter allows the format ['foo = ?', bar] for this purpose, but joins does not. conditions参数允许格式['foo = ?', bar]用于此目的,但joins不允许。

I don't want to use find_by_sql because then I would need to add the joins and conditions which are part of the model's default scope (that would not be DRY). 我不想使用find_by_sql因为那时我需要添加连接和条件,它们是模型默认范围的一部分(不会是DRY)。

Edit: My table structure is essentially this: 编辑:我的表结构基本上是这样的:

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

Note that this is a read-only database which Rails only has limited involvement with. 请注意,这是一个只读数据库,Rails只有有限的参与。 I am not planning to set up models for all the tables; 我不打算为所有表格设置模型; I just want to do a simple query as described above, without exposing myself to SQL injection attacks. 我只想进行如上所述的简单查询,而不会让自己暴露于SQL注入攻击。

The answer I found is to use the .sanitize method on the model: 我找到的答案是在模型上使用.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) + ')',
)

If you find a better solution, please post it! 如果您找到更好的解决方案,请发布!

This seems to be more what you were trying to do. 这似乎是你想要做的更多。

products = Product.find(pids,
    :select => 'products.*, P.code',
    :joins => sanitize_sql_array [
      'left join product_dist_match P on P.pid = products.pid and P.cid = ?', 
       cid
    ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM