rails helper方法如何:attribute_changed? 在Rails 3.2.15中有效吗?
这是我需要的情况:如果用户的电子邮件已更改,则生成用户确认代码
我有型号:
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
宏的修饰符。 即puts "hi" if :some_condition?
它与puts "hi" if :some_condition?
( if
不是这里puts
方法的输入)。
你想要的是将一个:if
选项传递给after_update
宏,如下所示:
after_update :generate_confirm_code, if: :email_changed?
请注意, if:
现在根植于after_update
宏的options散列中。
另请参阅ActiveRecord回调的Rails指南 。