Calling a method from another controller

后端 未结 4 732
逝去的感伤
逝去的感伤 2020-12-04 18:09

If I\'ve got a method in a different controller to the one I\'m writing in, and I want to call that method, is it possible, or should I consider moving that method to a help

相关标签:
4条回答
  • 2020-12-04 18:26

    Try and progressively move you methods to your models, if they don't apply to a model then a helper and if it still needs to be accessed elsewhere put in the ApplicationController

    0 讨论(0)
  • 2020-12-04 18:27

    I don't know any details of your problem, but maybe paths could be solution in your case (especially if its RESTful action).

    http://guides.rubyonrails.org/routing.html#path-and-url-helpers

    0 讨论(0)
  • 2020-12-04 18:42

    If you requirement has to Do with some DB operations, then you can write a common function (class method) inside that Model. Functions defined inside model are accessible across to all the controllers. But this solution does to apply to all cases.

    0 讨论(0)
  • 2020-12-04 18:48

    You could technically create an instance of the other controller and call methods on that, but it is tedious, error prone and highly not recommended.

    If that function is common to both controllers, you should probably have it in ApplicationController or another superclass controller of your creation.

    class ApplicationController < ActionController::Base
      def common_to_all_controllers
        # some code
      end
    end
    
    class SuperController < ApplicationController
      def common_to_some_controllers
        # some other code
      end
    end
    
    class MyController < SuperController
      # has access to common_to_all_controllers and common_to_some_controllers
    end
    
    class MyOtherController < ApplicationController
      # has access to common_to_all_controllers only
    end
    

    Yet another way to do it as jimworm suggested, is to use a module for the common functionality.

    # lib/common_stuff.rb
    module CommonStuff
      def common_thing
        # code
      end
    end
    
    # app/controllers/my_controller.rb
    require 'common_stuff'
    class MyController < ApplicationController
      include CommonStuff
      # has access to common_thing
    end
    
    0 讨论(0)
提交回复
热议问题