代码之家  ›  专栏  ›  技术社区  ›  Mark Eirich

联接子句中的Rails ActiveRecord转义变量

  •  8
  • Mark Eirich  · 技术社区  · 14 年前

    此查询有效,但对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})",
    )
    

    如何正确地转义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注入攻击。

    2 回复  |  直到 14 年前
        1
  •  15
  •   Mark Eirich    14 年前

    我找到的答案是使用 .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) + ')',
    )
    

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

        2
  •  2
  •   littleforest    10 年前

    这似乎更像是你想要做的。

    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
        ]