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
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With