Rails, how to sanitize SQL in find_by_sql

后端 未结 6 1281
孤城傲影
孤城傲影 2020-12-06 00:55

Is there a way to sanitize sql in rails method find_by_sql?

I\'ve tried this solution: Ruby on Rails: How to sanitize a string for SQL when not using fi

6条回答
  •  天命终不由人
    2020-12-06 01:42

    I made a little snippet for this that you can put in initializers.

    class ActiveRecord::Base  
      def self.escape_sql(array)
        self.send(:sanitize_sql_array, array)
      end
    end
    

    Right now you can escape your query with this:

    query = User.escape_sql(["Update users set active = ? where id = ?", true, params[:id]])
    

    And you can call the query any way you like:

    users = User.find_by_sql(query)
    

提交回复
热议问题