Where to put Ruby helper methods for Rails controllers?

流过昼夜 提交于 2019-11-27 18:55:01

You should define the method inside ApplicationController.

John Cleary

For Rails 4 onwards, concerns are the way to go. There is a decent article here http://richonrails.com/articles/rails-4-code-concerns-in-active-record-models

In essence, if you look in your controllers folder you should see a concerns sub-folder. Create a module in there along these lines

module EventsHelper
  def do_something
  end
end

Then, in the controller just include it

class BadgeController < ApplicationController
  include EventsHelper

  ...
end

you should define methods inside application controller, if you have few methods then you can do as follow

class ApplicationController < ActionController::Base    
  helper_method :first_method
  helper_method :second_method

  def first_method
    ... #your code
  end

  def second_method
    ... #your code
  end
end

You can also include helper files as follow

class YourController < ApplicationController
  include OneHelper
  include TwoHelper
end

You can call any helper methods from a controller using the view_context, e.g.

view_context.my_helper_method

Ryan Bigg response is good.

Other possible solution is add helpers to your controller:

class YourController < ApplicationController
  include OneHelper
  include TwoHelper
 end

Best Regards!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!