2017-10-18 193 views
0

我在控制器内创建了一个私有方法。如何在模型更新后执行控制器私有方法?

private 
def update_mark 
... 
... 
end 
  • 我希望每当一条记录被更新到任何我们有四种模式被称为我的私有方法。我们应该怎么做 ?
  • 我读过“after_save”或“after_commit”可以使用。但我不确定,哪一个可以使用。

有人可以提供一个例子,我们如何才能做到这一点?

回答

0

在你的模型(假设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 
+0

谢谢你答案。那么我是否需要为每个模型定义方法?我看到你提到了“@instance = a.update”,但是我希望我的私有方法在更新发生在其他模型上时调用,即模型B.在这种情况下,我需要定义类似[this](https ://gist.github.com/gknathk/be575fdb63eeb1a1feb65846b9528bc9)。 –

+0

@GokulnathKumar增加了一个'klass'方法,这只是基于params来决定选择哪个模型。您可以拥有自己的逻辑,可以选择哪个模型类,并且可以使用单个方法来处理它。 – AnkitG

+0

完美谢谢! –

相关问题