0

I'm trying to compose programmatically the .where() clause.

It looks like

Post.where("description ?", @composite)

Where @composite is a string which is constructed before. It may be something like = 'ABCD' or maybe IS LIKE 'ABCD' etc.

Problem is in the resulting SQL it's always single-quoted. For example:

Post Load (0.2ms)  SELECT `posts`.* FROM `posts` WHERE (description 'IS LIKE "ABCD"')

Is there any way to "un-quote" it?

valk
  • 9,363
  • 12
  • 59
  • 79

2 Answers2

1

The = and IS LIKE should not be part of the string you're passing in.

It's being single-quoted because that's precisely what the ? does: SQL-safed quoting.

If you want to completely construct the SQL yourself then do so, e.g.,

Post.where("description #{@composite}")

You'll need to sanitize the string yourself, which is easy since presumably you're constructing the = or IS LIKE part with input.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • That's the problem I tried to solve :) `Post.where("description #{@composite}")` is bad for SQL injection. – valk Aug 24 '14 at 13:27
  • @valk But you can't do it the way you're trying to, the `?` explicitly safes the input value. You need to safe it yourself if you're going to not use the built-in mechanisms. – Dave Newton Aug 24 '14 at 13:29
  • So the answer is, Rails doesn't know how to sanitize anything else than values for SQL :) – valk Aug 24 '14 at 14:13
  • @valk Nothing else needs sanitizing. – Dave Newton Aug 24 '14 at 14:21
  • Right, but would save time if there was sanitizing for whole chunks, no? – valk Aug 24 '14 at 14:48
  • @valk It's the same process whether you or Rails does it. But how would Rails guess your intent?! You're passing an arbitrary string that happens to contain sql- expecting Rails to guess what you mean is asking too much. – Dave Newton Aug 24 '14 at 16:17
0

Use this:

Post.where("description #{@composite}")
Ahmad Hussain
  • 2,443
  • 20
  • 27