Search code examples
sqlruby-on-railsactiverecordruby-on-rails-3.2sql-injection

Need to avoid SQL Injection in Rails3


I need the following code to be rewritten by avoiding SQL Injection in Rails 3.

some_table_name.joins("inner join #{table_name} on linked_config_items.linked_type = '#{class_name}' and linked_config_items.linked_id = #{table_name}.id").
        where("#{table_name}.saved is true and #{table_name}.deleted_at is null")

Here, table_name is dynamic and it will vary.


Solution

  • Finally, I had to rewrite my above query like this

    some_table_name.joins(self.class.superclass.send(:sanitize_sql_array,"inner join #{table_name} as t1 on linked_config_items.linked_type = '#{class_name}' and linked_config_items.linked_id = t1.id")).
              where("t1.saved is true and t1.deleted_at is null")
    

    Here, 'self.class.superclass' is 'ActiveRecord::Base'