I want to use the current_page? in the rails controller.

Asked 2 years ago, Updated 2 years ago, 77 views

If you use current_page?(hoge_path) in the controller, you will get the following error:

 undefined method `current_page?'

How should I determine the path within the controller?

ruby-on-rails ruby

2022-09-30 21:12

3 Answers

Use url_for to find out what the action of a certain controller will be like.
Compared to xxxx_path, I think the following is true:

class UsersController<ApplicationController
  def index
    users_path==url_for(controller:controller_name, action:action_name, only_path:true)
  end
end


2022-09-30 21:12

If you call ApplicationController.helpers.xxxxxxxx in the controller, you can use helper, but current_page? does not work.

I think what I want to do is check the current controller action, so

  • controller_name
  • action_name

How about judging by ?


2022-09-30 21:12

Regardless of whether this approach is well behaved or not, you can use current_page? by including ActionView::Helpers::UrlHelper.

class UsersController<ApplicationController
  include ActionView::Helpers::UrlHelper

  def index
    Rails.logger.debug current_page?(users_path)#=>true
    @users=User.all
  end
end


2022-09-30 21:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.