Search code examples
rubyruby-on-rails-3actioncontroller

How to retrieve the controller class from within a view/helper in Rails 3?


I know about controller_name returning a string containing the controller's name but how can I retrieve the controller class (or object) from within a helper?

EDIT: The solution should also work when the controller is namespaced (eg. Admin::PostsController)


Solution

  • You can use the constantize method, like:

    controller_name.constantize
    

    Though I'm not sure how it will behave if you have a namespaced controller.

    Update:

    That one won't work for all controller names and/or namespaces. Though one can use the #controller method in combination with #class:

    controller.class