0

What is the difference between the following:

@user = User.find_by(["username = ?", params['username']])
User Load (0.5ms)  SELECT  "users".* FROM "users"  WHERE (username = '2YY') LIMIT 1

and this:

@user = User.find_by(username: params['username'])
User Load (0.5ms)  SELECT  "users".* FROM "users"  WHERE "users"."username" = '2YY' LIMIT 1

The only difference I see is the parenthesis. Is this how it escapes bad input? Should I be validating username perhaps with regex? E.g. username can only contain text or numbers, should I validate this before going to database or does this @user = User.find_by(["username = ?", params['username']]) protect me?

And also if both of these queries have the same output but the first is safe, then what it the point of the second query?

2 Answers 2

1

There are differences but proper quoting of params['username'] isn't one of them. In both cases, ActiveRecord will take care of properly escaping the username so you don't have to worry about that.

Some differences:

  1. The first form uses an SQL snippet that you write rather than leaving it up to AR to write the SQL. If you need conditions that AR doesn't really understand – such as function calls (find_by(['lower(username) = ?', x])), boolean expressions (find_by('some_boolean_column and username = ?', x])), etc. – then the the first form lets you use them whereas the second form is more limited.
  2. The second form includes the table name ("users") and quotes the column name ("username"). Including the table name is useful if you have JOINs and need to disambiguate a column name. Quoting the column name is useful if you have column names that are case sensitive or contain special characters.

The above are rarely an issue when using a simple find_by like you are. The second form:

@user = User.find_by(username: params['username'])

is usually preferred and considered more Railsy because it hides the details of the database interaction and lets you pretend that SQL doesn't exist.

2
  • 2
    And just to be clear on where the protection lies -- the form that doesn't protect you, and which you should probably never ever use: User.find_by(["username = #{params['username']}"]). Always let Rails insert parameters into the query, never do it yourself by concatenation or interpolation.
    – Amadan
    Aug 25, 2014 at 1:13
  • Answer and comment. Exactly what I wanted to know. Thanks fellas! Aug 25, 2014 at 5:11
0

Both types of syntax are functionally equivalent in this case, and both will use Rails' built-in SQL sanitization so users can't do anything nasty. There's no need for extra sanitization on your behalf, just make sure you're not interpolating/concatenating the param into your SQL fragment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.