Rails 4 LIKE query - ActiveRecord adds quotes

前端 未结 7 1560
轮回少年
轮回少年 2020-12-02 09:07

I am trying to do a like query like so

def self.search(search, page = 1 )
  paginate :per_page => 5, :page =>          


        
相关标签:
7条回答
  • 2020-12-02 09:46

    ActiveRecord is clever enough to know that the parameter referred to by the ? is a string, and so it encloses it in single quotes. You could as one post suggests use Ruby string interpolation to pad the string with the required % symbols. However, this might expose you to SQL-injection (which is bad). I would suggest you use the SQL CONCAT() function to prepare the string like so:

    "name LIKE CONCAT('%',?,'%') OR postal_code LIKE CONCAT('%',?,'%')", search, search)

    0 讨论(0)
提交回复
热议问题