2015-04-03 54 views
0

我想爲各種控制器添加一個狀態問題,因爲所有這些控制器共享相同的狀態功能。Rails 4 Controller Concern初始化程序

狀態可以是「活動」,「不活動」或「存檔」。如果添加到特定的控制器前。 bars_controller這些方法應該是這樣的:

def activate 
    @bar.activate! 
    redirect_to(:back) 
end 

def deactivate 
    @bar.deactivate! 
    redirect_to(:back) 
end 

def archive 
    @bar.archive! 
    redirect_to(:back) 
end 

我提出上面我所關注的被稱爲Foo和我在我的控制器,這樣包括富:搬家時

include Foo 

我有問題這些方法令人擔憂,是Model實例未定義。

如何概括我關心的代碼中的「@bar」部分?這將使我能夠使用包括Baz在內的多個模型實例的關注。我試過使用「self」,但是引用了Controller實例而不是Model實例。

+0

如果我理解這一點沒錯,你將需要初始化這個@bar某處。由於您在許多控制器中使用它,因此在應用程序控制器中執 – 2015-04-03 12:24:10

+0

您的'@ bar'定義在哪裏?你應該有一個像'def find_bar @bar = Bar.find(params [:id]);結束'某處。 – pierallard 2015-04-03 12:53:47

+0

@ForgetTheNorm,「bar」在「before_action」中定義。如果它在一個特定的控制器本身,那麼「bar」不是問題。當我將這些方法轉移到更普遍的問題時,會出現問題。我不能稱之爲「酒吧」,因爲我需要將「關注」用於「巴茲」。 – Herm 2015-04-03 13:17:50

回答

0

您的關注可能是這樣的:

module Foo 
    extend ActiveSupport::Concern 

    def activate 
     render text: bar.to_json 
    end 

    def deactivate 
     render text: bar.to_json 
    end 

    def archive 
     render text: bar.to_json 
    end 

    private 

    def bar 
     # 'demodulize' isn't necessary if you're working outside of namespaces 
     params[:controller].classify.demodulize.constantize.find(params[:id]) 
    end 

end 

和你的路線將使用一個關注以及受益:

concern :statusable do 
    member do 
     get :activate 
     get :deactivate 
     get :archive 
    end 
end 

resources :alphas, :bravos, :charlies, concerns: :statusable