【问题标题】:Calling a method of another controller调用另一个控制器的方法
【发布时间】:2016-06-10 13:54:12
【问题描述】:

我有名为 ChildrenFatherMother 的控制器,我需要从 ChildrenController 调用 FatherControllerMotherController 的方法。

我需要将 JSON 数据传递给两个控制器(不是在同一个请求中get_details 方法来自set_details 方法的ChildrenController。我将根据某些条件调用任何控制器方法。

两个控制器中的get_details 方法没有路由。 我不需要任何辅助方法来编写。

我需要调用多个控制器的方法,而不是通过继承。

父控制器

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

如果有任何其他方法可以做到这一点,请帮助或建议我。

谢谢。

【问题讨论】:

  • 控制器层可能不是您希望此逻辑所在的位置。您可能需要考虑将其推送到模型/业务逻辑层,而不是尝试在控制器之间传递数据。例如,创建一个普通的 Ruby 对象,该对象知道如何处理逻辑并将返回您需要的数据。 details = DomainObject.new(data).process 在该 DomainObject 中,你可以做任何你需要的事情来提取你想要的数据。
  • 我同意@CarlosRamirezIII 的观点,这可能属于模型。但是,如果您真的想要在控制器中使用它,您可以尝试使用通用方法制作 Concern 并将其包含在需要该方法的每个控制器中。更多关于关注的信息可以在这里找到:stackoverflow.com/questions/14541823/…
  • @Dan 我同意你的看法。感谢您的评论。

标签: ruby-on-rails ruby-on-rails-4 controller


【解决方案1】:

简单。制作方法.self

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

然后:

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

【讨论】:

  • 不适用于 rail 5+ : uninitialized constant ChildrenController::MotherController ...
【解决方案2】:

要么从控制器中删除此逻辑,要么在 ApplicationController 中定义它,您的所有控制器都从该 ApplicationController 继承。

【讨论】:

    【解决方案3】:

    您为什么不简单地将您的函数或方法写入 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
    

    【讨论】:

    • 您可以添加关系以允许直接从母模型访问子模型,并对子模型进行您希望的任何操作
    猜你喜欢
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多