Get current controller name/action name from view

13,017 views
Skip to first unread message

michael_teter

unread,
May 11, 2008, 2:22:17 AM5/11/08
to Ruby on Rails: Talk
Hi.

I swear I found this in the group archives, but now I cannot find this
in the group or elsewhere online!

In a view I would like to get the current controller name and action
that was used to get here.

For example, I have a template that I'm using from two different
controllers (and four different actions in each controller), such
as :controller => "my_view", :action => "current" (or "expired", or
"fixed", etc.)

In this template I'm constructing some links to specific parameter
calls of this same template, and I need to know which controller was
used and what action was called to get us here. I thought it was
something like this:

link_to "This Year", :controller => @controller.name, :action =>
@controller.action

The only thing I've found in the api that looks remotely similar is
UrlHelper's current_page(), but that's not quite what I'm after, as I
don't want to test something, I just WANT that something :)

Thanks.

Ruby Freak

unread,
May 11, 2008, 12:25:34 PM5/11/08
to Ruby on Rails: Talk
Here is a link to what I think you are looking for

http://www.postal-code.com/mrhappy/blog/2007/01/18/rails-knowing-the-current-action-in-a-view/

Good luck.

Phlip

unread,
May 11, 2008, 1:39:35 PM5/11/08
to rubyonra...@googlegroups.com
> In a view I would like to get the current controller name and action
> that was used to get here.

params[:controller]
params[:action]

> In this template I'm constructing some links to specific parameter
> calls of this same template, and I need to know which controller was
> used and what action was called to get us here. I thought it was
> something like this:
>
> link_to "This Year", :controller => @controller.name, :action =>
> @controller.action

Use url_for (or a named route), then _don't_ pass the controller in. Url_for
will find the controller in params if you don't pass it in.

(Write tests for all this stuff, using assert_xpath, to detect you are getting
the links you expect!)

michael_teter

unread,
May 11, 2008, 2:27:26 PM5/11/08
to Ruby on Rails: Talk
Excellent, thanks!

I also just found this:
http://snippets.dzone.com/posts/show/4391

<%= controller.controller_name %>
<%= controller.action_name %>
Reply all
Reply to author
Forward
0 new messages