这是我的情况 我需要:如果用户的电子邮件已更改,则生成用户确认码
我有 型号:
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 可以保存用户上次访问的时间
class ApplicationController < ActionController::Base
...
def update_last_visit
current_user.update_last_visit if current_user
end
...
end
问题从这里开始: 每次我重新加载页面时,我的确认码都会更改,即使我没有更改电子邮件也是如此。似乎更新 last_visit 也会更改 confirmation_code 但为什么呢?
最佳答案
您的 after_update
宏的语法略有错误。正如您现在看到的那样,if :email_changed?
实际上只是一个修饰符,用于决定在加载 User 类时是否运行 after_update
宏。 IE。它与 puts "hi"if :some_condition?
相同(if
不是此处 puts
方法的输入)。
您想要的是将 :if
选项传递给 after_update
宏,如下所示:
after_update :generate_confirm_code, if: :email_changed?
请注意,if:
现在 Root 于 after_update
宏的选项散列中。
关于ruby-on-rails - Rails 辅助方法 :attribute_changed? 在 Rails 3.2.15 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23846850/