Search code examples
mysqlruby-on-railsruby-on-rails-4activerecordsql-injection

Safe way to send parameters to stored procedure in ROR


I will make simpler than it is to get the answer I need without make you read a lot of code.

MySQL stored procedure:

CREATE PROCEDURE add_player
(IN name varchar(100),
 IN isTrue boolean)
BEGIN
  START TRANSACTION;

  insert into tags (name,is_player) values (name,isTrue);

  COMMIT;
END //

player_controller.rb

ActiveRecord::Base.connection.execute("call add_player('#{name}', #{is_player})")

Two problems I see(if you see more - say):

  1. if name contains ' it breaks the call
  2. sql injection - I don't use ? as parameters when I call the stored procedure. The reason is that it's just not working when I'm try with ?. I tried also change it to Player.where("add_player(?,?)",name,is_player)

Solution

  • Did you try something like this ?

    ActiveRecord::Base.connection.execute("call add_player(#{ActiveRecord::Base.sanitize(name)}, #{is_player})")
    

    There is another way suggested on the following SO link

    using sanitize_sql_array to escape strings

    The only problem is that sanitize_sql_array is not a public method