3

Railscast Episode 275 - How I test uses the following code to send password resets to users:

def send_password_reset
  generate_token(:password_reset_token)
  ....
  ... etc
end

def generate_token(column)
  begin
    self[column] = SecureRandom.urlsafe_base64
  end while User.exists?(column => self[column])
end

My question regards the penultimate line of code: end while User.exists?(column => self[column]) which works fine as is, but causes my specs to fail if I swap out the hash-rocket i.e. end while User.exists?(column: self[column])

Failure/Error: user.send_password_reset
   ActiveRecord::StatementInvalid:
   SQLite3::SQLException: no such column: users.column: SELECT  1 FROM "users"  WHERE "users"."column" = 'Y7JJV4VAKBbf77zKFVH7RQ' LIMIT 1

Why is this happening? Are there situations where you must use a hash-rocket, and are there any guidelines regarding this?

stephenmurdoch
  • 34,024
  • 29
  • 114
  • 189

1 Answers1

9

column in that line of code isn't a symbol, its a variable, so you need to use the hash rocket. column: self[column] would build a hash where the key was the symbol :column, not the value of the variable column, which is what you want.

The new syntax is just a shortcut when using a literal symbol for a key (key: value instead of :key => value). If you are using a variable key the => syntax is still required.

Carl Zulauf
  • 39,378
  • 2
  • 34
  • 47
  • 4
    Not just any symbols, only symbols that are valid labels. `:$set`, for example, requires the hashrocket as do many other valid symbols. http://stackoverflow.com/a/10004344/479863 – mu is too short May 31 '12 at 19:23