2017-04-08 52 views
1

有時我需要從一個控制器使用另一個控制器的操作。我現在所做的是實例化它並使用它的操作,但它讓我覺得它不正確,所以我被告知不能有幾個同一個控制器的實例。如何鏈接Ruby On Rails中的控制器?

最佳實踐是什麼?非常感謝。

+1

這個問題在這裏回答http://stackoverflow.com/questions/128450/best-practices-for-reusing-code-between-controllers-in-ruby-on-rails –

回答

1

這就是你如何鏈接控制器 使該方法。 self

class TestController < ApplicationController 
    def self.get_details(data) 
    end 
end 

然後:

class ChildrenController < ApplicationController 
    def set_details   
    TestController.get_details(data) 
    end 
end 

其他選項來創建庫模塊

LIB/common_stuff.rb

module CommonStuff 
    def common_thing 
    # code 
    end 
end 

應用程序/控制器/ my_controller.rb

require 'common_stuff' 
class MyController < ApplicationController 
    include CommonStuff 
    # has access to common_thing 
end 
1

Rails中的良好做法是將公共邏輯移至service/module/lib/gem。如果您需要的操作僅針對控制器,那麼您可以定義抽象控制器並從中繼承您的控制器。就像你用ApplicationController做的那樣。