2016-06-10 100 views
1

我有一個名爲ChildrenFatherMother控制器,我需要從ChildrenController調用FatherControllerMotherController的方法。調用另一個控制器的方法

我需要(不是在同一請求)從ChildrenControllerset_details方法get_details方法的JSON數據傳遞到兩個控制器。我打算根據某些條件調用任何控制器方法。

在兩個控制器中都有沒有路徑對於get_details方法。 我不需要任何助手方法來編寫。

我需要調用多個Controller的方法,而不是繼承。

父親控制器

class FatherController < ApplicationController 

    def get_details(data) 
    ## 
    ## I need to do some operation with the 'data' received from children controller. 
    end 

end 

母親控制器

class MotherController < ApplicationController 

    def get_details(data) 
    ## 
    ## I need to do some operation with the 'data' received from children controller. 
    end 

end 

兒童控制器

class ChildrenController < ApplicationController 

    data = { 
     "id":"2", 
     "expiry_date":"25-09-2016" 
    }.as_json 

    def set_details   
    ## get_details(data) -> FatherController 
    ## get_details(data) -> MotherController 
    end 

end 

請幫忙如何做到這一點還是建議我,如果有任何其他的方式來做到這一點。

謝謝。

+3

控制器層很可能不是你想要這個邏輯去住。您可能想考慮將其推向模型/業務邏輯層,而不是嘗試將數據從控制器傳遞到控制器。例如,創建一個普通的Ruby對象,該對象知道如何處理邏輯並將返回所需的數據。 'details = DomainObject.new(data).process'在這個DomainObject中,你可以做任何你需要的東西來提取你想要的數據。 –

+1

我同意@CarlosRamirezIII,這可能屬於模型。但是如果你真的想在控制器中使用它,你可以嘗試使用一種常用方法來關注「關注」,並將其包含在每個需要該方法的控制器中。關於關注的更多信息可以在這裏找到:http://stackoverflow.com/questions/14541823/how-to-use-concerns-in-rails-4 – Dan

+1

@丹我同意你。謝謝你的評論。 –

回答

8

簡單。使該方法.self

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

然後:

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

無論是從控制器刪除此邏輯或ApplicationController,其中所有的控制器都繼承定義它。

1

你爲什麼不你只需簡單的函數或方法進入MODEL

class MotherModel < ApplicationRecord 

    def self.mothermodel_method 
    end 
end 


class ChildController < ApplicationController 
    def access_mother_method 
     @result_from_mother_method = MotherModel.mothermodel_method 
    end 
end 
+1

您可以添加關係以允許直接從母親模型訪問子模型,並在子模型上執行您希望的任何操作 – Emma

相關問題