3

How do I remove the quotation marks around a variable so that I can use the LIKE operator in find_by_sql in rails?

@entries1 = Entry.find_by_sql(["SELECT `entries`.name as name FROM `entries` where `entries`.name like '%?%'",@something])

will yield

SELECT `entries`.name as name FROM `entries` where `entries`.name like '%'hello'%'

when @something = 'hello'

JMT
  • 63
  • 3
  • 7

4 Answers4

3

Instead of putting the percent symbols in the SQL, add them to the variable you're injecting (after escaping percent signs/underscores already present!)

"%#{@something.gsub('%', '\%').gsub('_', '\_')}%"
Fustrate
  • 41
  • 4
2

You could use concat inside the database:

Entry.find_by_sql([
  "SELECT ... `entries`.name like concat('%', ?, '%')",
  @something
])

or you can add the wildcards in Ruby:

Entry.find_by_sql([
  "SELECT ... `entries`.name like ?",
  "%#{@something}"
])

Note that other databases will want to see '%' || ? || '%' or '%' + ? + '%' instead of the concat call.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
2

@entries1 = Entry.select('name').where('name like ?',"%#{@something}%"]) should do the same

Alter Lagos
  • 12,090
  • 1
  • 70
  • 92
1

You need four '%' around the search value and must precede each with delimiter ‘\’.

For example search_val can be “” or “031”, etc...

find_by_sql([ "select  * from tableX where id like '\%\%#{search_val}\%\%'" ])
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164