Search code examples
mysqlruby-on-railsselectsql-injectionsanitization

How to use the '?' symbol in a MySQL select in Ruby On Rails?


I need to get the pertinence of a MySQL Fulltext search in my Rails 4.2 app. So I need an alias (pertinence) in the select clause.

The problem is to use the '?' symbol as in a where clause, but in a select:

Model.select("articles.*, MATCH (name) AGAINST (? IN BOOLEAN MODE) AS pertinence", @search).where(...).order("pertinence DESC")

If I do:

Model.select('articles.*, MATCH (name) AGAINST ("' + @search + '" IN BOOLEAN MODE) AS pertinence').where(...).order("pertinence DESC")

I can have issues with quotes in @search (no sanitization) and SQL injection.

So how to perform this kind of queries with Active Record ?

Thanks


Solution

  • You can manually sanitize the search parameter.

    search_param = ActiveRecord::Base::sanitize(@search)
    
    Model.select("articles.*, MATCH (name) AGAINST (#{search_param} IN BOOLEAN MODE) AS pertinence").where(...).order("pertinence DESC")