Ben Richardson
Ben Richardson

Reputation: 37

How do I prevent interpolation of this Ruby string?

I am using Ruby on Rails and I have a location in my database with the name:

1A J@ck$on & S0n's #{10}

I am receiving this name via a webhook and then searching my database with it however it does not find the location name ( it is instead searching for the interpolated name:

1A J@ck$on & S0n's 10

How can I receive this string via a webhook like this:

@location = inbound_webhook_request['location']

And then put it in a pg "like" query as shown below:

Location.where("name ~* ?", @location['name'])

Without it being interpolated along the way?

Upvotes: 1

Views: 292

Answers (1)

Tom Lord
Tom Lord

Reputation: 28305

The string is not being interpolated. I'm not sure what led you to that assumption. However:

Location.where("name ~* ?", @location['name'])

This is not a LIKE operation, it's a POSIX regexp (case insensitive) operation.

Assuming you actually did want to perform a LIKE operation, not a regular expression search, you can do this:

Location.where("name LIKE ?", "%#{@location['name']}%")

or, using the shorthand syntax from the above linked documentation:

Location.where("name ~~ ?", "%#{@location['name']}%")

For a case-insensitive LIKE, you can use ILIKE or ~~*.

If the user input needs to be further sanitised, see this answer.

Upvotes: 3

Related Questions