2017-10-18 189 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

完美謝謝! –

相關問題