【问题标题】:changed? depreaction Rails 5.1.2改变了吗?弃用 Rails 5.1.2
【发布时间】:2017-07-16 10:43:50
【问题描述】:

在保存记录之前进行设计,它会检查属性是否更改,如果更改则执行特殊操作:

def send_devise_notification(notification, *args)
  # If the record is new or changed then delay the
  # delivery until the after_commit callback otherwise
  # send now because after_commit will not be called.

  if new_record? || changed?
    pending_notifications << [notification, args]
  else
    # Devise: send emails with background job
    devise_mailer.send(notification, self, *args).deliver_later
  end
end

http://www.rubydoc.info/github/plataformatec/devise/Devise%2FModels%2FAuthenticatable%3Asend_devise_notification

以下行现在给了我一个弃用:

if new_record? || changed? 

DEPRECATION WARNING: The behavior of 'changed?' inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after 'save' returned (e.g. the opposite of what it returns now). To maintain the current behavior, use 'saved_changes?' instead.

当我使用saved_changes? 而不是changed? 时,代码将无法正常工作,因为在此步骤中尚未保存记录

例如

user.email = "hello@example.com"
user.changed? => true
user.saved_changes? => false

我应该改用哪种方法?如何防止弃用警告?谢谢

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 devise


    【解决方案1】:

    该消息意味着changed? 在 after_create 或 after_save 等回调之后的行为会有所不同。因为记录已经被保存了,所以你可以使用saved_changes? 来代替它,它可以很好地处理这些回调

    但是如果你想在回调之前使用它,例如 before_save 然后离开changed?,不要替换它,因为它会像以前一样正常工作

    如果你不关心对象是否被保存。你可以检查他们两个new_record? || saved_changes? || changed?

    对于您提到的有关更改用户电子邮件的示例。 devise 将在保存后发送确认,所以 saved_changes? 应该可以正常工作!

    【讨论】:

      【解决方案2】:

      您应该改用saved_changes?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-02
        • 2011-01-13
        • 1970-01-01
        • 1970-01-01
        • 2012-11-03
        • 2010-11-20
        相关资源
        最近更新 更多