Calling a method of another controller

2019-06-24 18:42发布

问题:

I have controllers named Children and Father and Mother where I need to call a method of FatherController and MotherController from ChildrenController.

I need to pass a JSON data to the both controller(not at the same request) get_details method from set_details method of ChildrenController. I am going to call any of the controllers method based on some conditions.

There is no route for get_details method in both controllers. I don't need any helper methods to write.

I need to call more than one Controller's method, not by Inheriting.

Father controller

class FatherController < ApplicationController

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

end

Mother controller

class MotherController < ApplicationController

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

end

Children controller

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

Please help how to do this or suggest me if there is any other way to do this.

Thanks.

回答1:

Easy. Make the method .self

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

And then:

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


回答2:

Either remove this logic from the controller or define it in the ApplicationController, of which all your controllers are inheriting from.



回答3:

Why dont you simply write your function or method into the 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