Teej
Teej

Reputation: 12873

SQL injection on Activerecord query

I currently have this:

products = Product.select("DISTINCT(products.id), products.*").joins("JOIN (SELECT * FROM `shop_categorizations` WHERE (shop_categorizations.shop_category_id IN (SELECT id FROM `shop_categories` WHERE (`shop_categories`.shop_id = #{id} AND (`shop_categories.id` IN (#{shop_categories})))))) AS `shop_categorizations` ON `shop_categorizations`.`product_id` = `products`.`id`");

I was thinking that this query would be susceptible to sql injection. How would I make this query safe from it. I assume binding but I don't know how to apply it here.

A background on the models if it helps:

Product belongs to ShopCategory
ShopCategory belongs to Shop

Upvotes: 1

Views: 867

Answers (1)

Innerpeacer
Innerpeacer

Reputation: 1321

In your case, I think you don't need binding. Both the parameters are Fixnum, you can just convert the input to Fixnum to guard against SQL injection:

JOIN (SELECT * FROM shop_categorizations WHERE (shop_categorizations.shop_category_id IN (SELECT id FROM shop_categories WHERE (shop_categories.shop_id = #{id.to_i} AND (shop_categories.id IN (#{shop_categories.map(&:to_i)})))))) AS shop_categorizations ON shop_categorizations.product_id = products.id

If you really need to handle string data types, you can prevent SQL injection by escaping/quoting it, see: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Quoting.html#method-i-quote

Upvotes: 3

Related Questions