繁体   English   中英

rails helper方法如何:attribute_changed? 在Rails 3.2.15中有效吗?

[英]How does rails helper method :attribute_changed? works in 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指南

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM