【问题标题】:Pass variable between callbacks在回调之间传递变量
【发布时间】:2015-10-07 12:21:03
【问题描述】:

我有一个如下所示的 ActiveRecord 模型,目标是在用户完成他的(之前未完成的)个人资料时发送通知:

class User < ActiveRecord::Base
  before_update :check_profile
  after_update :notify_profile_completed

  def is_complete?
    # run some tests
  end

  private
  def check_profile
    @complete = is_complete?
  end

  def notify_profile_completed
    if is_complete? and not @complete
      # send notification
    end
  end
end

如果我运行更新,当到达@complete = is_complete? 代码时,出现问题并且整个更新失败且没有任何错误消息。

我想这不是在回调之间传递变量的方法......那该怎么做呢?

【问题讨论】:

  • 我的 2 美分:ActiveRecord 回调不应该做任何与持久性没有直接关系的事情。 (包括发送通知)。声明了一些优点here
  • 这是一个很好的建议......按照您在本文中指出的方式实现通知逻辑可能会解决我的问题。谢谢

标签: ruby-on-rails rails-activerecord


【解决方案1】:

试试这个

class User < ActiveRecord::Base
  before_update :check_profile
  after_update :notify_profile_completed

  def is_complete?
    # run some tests
  end

  private
  def check_profile
    self.complete = is_complete? # Assuming complete is a column in User class
  end

  def notify_profile_completed
    if is_complete? and !complete
      # send notification
    end
  end
end

因为您不会在一种方法中将@complete 设置为另一种方法

【讨论】:

  • 好吧,问题在于complete 不是 User 类中的列,因为我不想存储确定的临时数据。没有其他方法可以在实例内部传递数据吗?
  • 问题是,当第一次调用和第二次调用时,它可能不是同一个实例,否则,你的原始代码会工作得很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-03
  • 1970-01-01
  • 2013-10-30
  • 2018-03-07
  • 2020-07-02
相关资源
最近更新 更多