【问题标题】:rails - after_update occurring on .save for new objectrails - after_update 发生在新对象的 .save 上
【发布时间】:2013-12-12 22:47:03
【问题描述】:

我有两个模型:UserNotification 和 Schedule。创建计划时,会创建一种类型的用户通知(第一行代码)。更新计划时,会创建另一种类型的用户通知(第二行代码)。出于某种原因, after_update 在保存后发生(我只希望它在更新后发生)。这是代码中的代码:

class Schedule < ActiveRecord::Base
   after_save 'UserNotification.schedule_created(@user)'
   after_update 'UserNotification.schedule_updated(@user)'
end

我是不是错过了什么。如何让 after_save 仅在我说 @schedule.save 之后发生,而 after_update 仅在我执行 @schedule.update_attributes(...) 之后发生?如果有帮助,这里是控制器代码:

if @schedule.save   
    flash[:notice] = "Successfully created schedule."
    redirect_to profile_path(current_user.profile_name)  #change to project path later
end

【问题讨论】:

    标签: ruby-on-rails oop callback ruby-on-rails-4 rails-activerecord


    【解决方案1】:

    在后台,save 在新记录上调用 create,在持久记录上调用 update

    创建和更新记录时都会调用after_save 回调。

    after_createafter_update 回调分别在新记录和持久记录上调用。

    如果您只希望它在创建对象后运行,则需要将 after_save 回调更改为 after_create

    有关 ActiveRecord 回调的更多信息,请参见 the Rails documentation

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    • 2015-07-18
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多