stephenmurdoch
stephenmurdoch

Reputation: 34643

Ruby hash rockets vs 1.9 syntax

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?

Upvotes: 3

Views: 766

Answers (1)

Carl Zulauf
Carl Zulauf

Reputation: 39568

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.

Upvotes: 9

Related Questions