开发者

Rails: Where to define a helper method that will be available to several controllers?

开发者 https://www.devze.com 2023-02-05 17:15 出处:网络
I would like to define a helper method, my_method, that will be available inside BuyersController methods (like index, create, e.t.c.).

I would like to define a helper method, my_method, that will be available inside BuyersController methods (like index, create, e.t.c.).

I tried to define it in app/helpers/application_helper.rb but it didn't work:

undefined method `my_method' for #<BuyersController:0x26df468>

It should be in some shared开发者_如何学Python place because I want to use it in other controllers also. This is why I tried app/helpers/application_helper.rb.

What is the right place to define it ?


It should be in app/controllers/application_controller.rb

The app/helpers/application_helper.rb is for shared view helpers.


You should include the application helper module in your application controller so that its methods will be available everywhere (all controllers and views) during a request.

class ApplicationController < ActionController::Base
  helper ApplicationHelper
  …
end

See the API docs for the helper method


Starting from Rails 3 you could also call view_context.my_method inside your controller


Expanding on the accepted answer, if you did want to share a controller method with views, helper_method seems well suited for this. Declaring a helper_method in the controller makes it accessible to the views.

class ApplicationController < ActionController::Base
  helper_method :current_user, :logged_in?

  def current_user
    @current_user ||= User.find_by(id: session[:user])
  end

  def logged_in?
    current_user != nil
  end
end


Before rails 4, helpers with the same controller names will be only available in their controllers and views. Starting from rails 4, all helpers are available for all controllers (if you included them) and views. With that said, all helpers will be shared across your views.

Note: if you don't want this behavior for specific controllers, you can use clear_helpers, it will only include the helper with the same controller name.

For more information about using helpers see this

0

精彩评论

暂无评论...
验证码 换一张
取 消