Rails ActiveRecord escape variable in join clause

Viewed 6243

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.

2 Answers
Related