SQL query in Rails using % and LIKE -
i trying execute sql query in rails app. following executes since looking exact match:
connection.query("select * test y=#{connection.quote(name)} order x asc")
i want use operator find partial matches. in sql like:
select * test y '%john%' order x asc
how do in ruby query? tried adding %
in few places doesn't work. errors query looking %'john'%
instead of '%john%'
connection.query("select * test y #{%connection.quote(name)%} order x asc")
you need add %
s in ruby before quoting:
connection.query("select * test y #{connection.quote('%' + name + '%')} order x asc")
connection.quote
add single quotes produce valid sql string literal , want %
s inside string literal, hence ruby string concatenation before connection.quote
called.
or in sql:
connection.query("select * test y '%' || #{connection.quote(name)} || '%' order x asc")
||
standard sql string concatenation operator, might need use concat
function or else if you're using database doesn't support sql.
you're better off using activerecord interface spickermann suggests need hand useful know how.
Comments
Post a Comment