Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape an '@' character in a SQL query / ActiveRecord

How do I escape an '@' query in a SQL query.

I am using ActiveRecord (3).

suite_scenarios = Scenario.where(suite_id: suite_id)
tag_pair = ["@regression","@daily_feature"]

tag_pair_scenarios = suite_scenarios.where("metadata LIKE '%#{tag_pair[0]}%'").where("metadata LIKE '%#{tag_pair[1]}%'")
like image 429
David West Avatar asked May 11 '17 18:05

David West


1 Answers

Borrowing from this answer explaining how to construct ILIKE queries with placeholder conditions, it seems you can construct your query like this:

suite_scenarios.
  where("metadata LIKE '%' || ? || '%'", tag_pair[0]).
  where("metadata LIKE '%' || ? || '%'", tag_pair[1]")

This has the added benefit of protecting you from SQL injection, in case tag_pair comes from user input (form params).

like image 140
messanjah Avatar answered Sep 18 '22 13:09

messanjah