rails helper 方法如何:attribute_changed?在 Rails 3.2.15 中工作? [英] How does rails helper method :attribute_changed? works in Rails 3.2.15?
问题描述
这是我的情况我需要:如果用户的电子邮件已更改,则生成用户确认码
Here is my situation I need: to generate user confirmation code if user's email have changed
我有型号:
class User < ActiveRecord::Base
...
after_update :generate_confirm_code if :email_changed?
...
def generate_confirm_code
self.confirmation_code = SecureRandom.urlsafe_base64.first(8)
self.confirmed = false
end
def update_last_visit
self.last_visit = Time.now.utc
save
end
...
end
在 application_controller 中还有一个方法 :update_last_visit 可以保存用户上次访问的时间
also have a method :update_last_visit in application_controller which saves user last visit time
class ApplicationController < ActionController::Base
...
def update_last_visit
current_user.update_last_visit if current_user
end
...
end
这里是问题开始:每次我重新加载页面时,我的确认码都会更改,即使我没有更改电子邮件.似乎更新 last_visit 也改变了 Confirmation_code 但为什么呢?
here is the problem starts: every time i reload the page my confirmation code changes, even when i did not change the email. Seems like updating last_visit also changes confirmation_code but why?
推荐答案
您的 after_update
宏的语法稍有错误.正如您现在所拥有的,if :email_changed?
实际上只是在加载 User 类时是否运行 after_update
宏的修饰符.IE.它与 puts "hi" if :some_condition?
相同(这里的 if
不是 puts
方法的输入).
You just have the syntax slightly wrong on your after_update
macro. As you have it now, the if :email_changed?
is actually just a modifier on whether or not to run the after_update
macro when loading the User class. I.e. it's the same as puts "hi" if :some_condition?
(the if
is non an input to the puts
method here).
您想要的是将 :if
选项传递给 after_update
宏,如下所示:
What you want is to pass an :if
option to the after_update
macro, like this:
after_update :generate_confirm_code, if: :email_changed?
请注意,if:
现在植根于 after_update
宏的选项哈希中.
Notice that the if:
is now rooted in the options hash of the after_update
macro.
另请参阅Rails 指南关于 ActiveRecord 回调.
这篇关于rails helper 方法如何:attribute_changed?在 Rails 3.2.15 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!