【问题标题】:Class methods don't work in after_create类方法在 after_create 中不起作用
【发布时间】:2018-01-31 02:58:51
【问题描述】:

我的消息模型在after_create 中调用create_notifications

def create_notifications
  if Message.where(id: 3).first.present? # This message exists!
    puts "Found message" # This never fires when run :after_create
  else
    puts "#{Message.count}" # Returns 1 in after_create, and 125 in console (it only sees the just-created message)
end

问题:Message.where(id:3) 在回调中运行时不返回任何内容。但是,它在控制台中运行时有效。此外,当我在创建消息后手动运行.create_notifications 时,它也可以工作。

为什么Message.whereMessage.count等在after_create中运行时不起作用?

【问题讨论】:

    标签: ruby-on-rails activerecord callback


    【解决方案1】:

    Message.unscoped.where(id: 3) 替换它有效。奇怪,因为我没有默认范围或任何东西。我猜 ActiveRecord 将 where 查询作用于 after_create 中刚刚创建的查询?

    【讨论】:

    • 你可以登录 Message.where(id: 3).to_sql 看看 AR 到底在做什么。
    • 原来它实际上是在更改默认范围。 github.com/rails/rails/issues/12305
    • 我发现默认作用域比它们的价值更麻烦,太多隐藏的逻辑不符合我的口味。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    相关资源
    最近更新 更多