Railscast Episode 275 - How I test uses the following code to send password resets to users:
Railscast第275集——我如何使用以下代码向用户发送密码重置:
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])
我的问题是关于倒数第二行代码:end while user .exist ?(column => self[column]),它的效果很好,但是如果我将hash-rocket(即end)替换为user,就会导致我的规范失败。(列:自我(列))
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?
为什么会这样?有没有什么情况下你必须使用hash-rocket,并且有关于这个的指导方针吗?
1 个解决方案
#1
7
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.
这行代码中的列不是符号,而是变量,所以需要使用哈希火箭。列:self[column]将构建一个散列,其中键是symbol:column,而不是变量列的值,这正是您想要的。
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.
在使用一个键的文字符号时,新语法只是一个快捷键(键:值而不是:key =>值)。如果您正在使用变量键,仍然需要使用=>语法。
#1
7
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.
这行代码中的列不是符号,而是变量,所以需要使用哈希火箭。列:self[column]将构建一个散列,其中键是symbol:column,而不是变量列的值,这正是您想要的。
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.
在使用一个键的文字符号时,新语法只是一个快捷键(键:值而不是:key =>值)。如果您正在使用变量键,仍然需要使用=>语法。