Rails 3: Call functions inside controllers

前端 未结 4 561
误落风尘
误落风尘 2020-12-29 11:31

If I want to have functions to be called inside controllers, where should I put them?

4条回答
  •  感动是毒
    2020-12-29 11:45

    if you want it to be local to a controller then all you need to do is to add it to the controller you wish to use.

    private
    def myfunction
      function code.....
    end
    

    to all controllers you can put it inside the application controller, because all controlers are sub classed.

    ApplicationController

    protected
    
    def myfunction
    
      function code.....
    
    end
    

    If you want access in your views then you can create a helper

    ApplicationHelper

    def myfunction
    
      function code...
    
    end
    

提交回复
热议问题