2016-06-10 102 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

相关问题