简体   繁体   中英

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

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM