简体   繁体   中英

Rails ActiveRecord escape variable in join clause

This query works, but is totally open to SQL injection:

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? The conditions parameter allows the format ['foo = ?', bar] for this purpose, but joins does not.

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).

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. 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.

The answer I found is to use the .sanitize method on the model:

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
    ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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