如何在模型更新后执行控制器私有方法?

How to execute a controller private method after a model update?

我在控制器中创建了一个私有方法。

private
def update_mark
...
...
end

谁能给我提供一个例子,说明我们如何才能做到这一点?

在您的模型中(比方说 A、B)添加一个将实例标记为已更新的方法

#A
class A < ApplicationRecord

  attr_reader :updated
  after_update :mark_updated

  private
  def mark_updated
     @updated = true
  end
end

#B
class B < ApplicationRecord
  attr_reader :updated
  after_update :mark_updated

  private
  def mark_updated
     @updated = true
  end
end

使用控制器中标记为已更新的实例变量

class DummyController < ApplicationController

  #after the action we call the private method    
  after_action :update_mark, only: [:your_method]

  #this is the method where your update takes place
  def your_method
    @instance = klass.find(params[:id])
    @instance.update
  end

  private

  # this is a model decider method which can figure out which model needs to 
  # be updated
  def klass
     case params[:type]
     when 'a'
       A
     when 'b'
       B
     end
  end

  def update_mark
    if @instance.updated
      #write code which needs to run on model update
    end
  end
 end