ruby-on-rails - 获取回调 ActiveRecord Rails 的当前名称

标签 ruby-on-rails activerecord

在模型上,用户有 after_create :apply_roleafter_update :apply_role,我想获取 apply_role 方法上回调的当前名称。

类似于:

def apply_role
 if callback_name == 'after_create'
    # other stuff here
 else
    # other stuff here
 end
end

我知道我可以在 after_createafter_update 之间设置不同的方法,但就我而言,在 after_createafter_update 上设置方法code> 除了一行之外没有什么不同,所以我想重构我的代码,我只需要一种方法来进行多个回调。

我怎样才能做到这一点?

最佳答案

尝试以下操作,我已经在代码本身的注释中描述了更改。

def User < ActiveRecord::Base
  after_save :apply_role # this will gets called in case of create as well as update

  def apply_role
    if id_changed?
      # code to handle newly created record
    else
      # code to handle updated record
    end
  end
end

关于ruby-on-rails - 获取回调 ActiveRecord Rails 的当前名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31933990/

相关文章:

ruby-on-rails - 如何在ruby-on-rails应用程序顶部使用dBpedia设置neo4j?

ruby-on-rails - 如何通过接受嵌套属性的关联为多对多创建新记录?

ruby-on-rails - Array.count 在本地工作正常但在 heroku 上中断

ruby-on-rails-3 - 在Rails 3中使用数组格式的find_by_sql

php - 在 Codeigniter 中对 WHERE 子句进行分组

html - Rails/Carrierwave 缩略图调整大小无法正常工作

ruby-on-rails - 在 HAML 中,如何将类添加到表单上的提交输入(按钮)

ruby-on-rails - 使用 Spork 和 Guard 时启动错误

ruby-on-rails - ActiveRecord:如何设置模型的 "changed"属性?

ruby-on-rails - 我怎样才能 "bump"具有最新评论的帖子并且让没有评论的新帖子出现在 Rails 的顶部?