views:

401

answers:

4

When using before_filter :login_required to protect a particular page, the link_to_unless_current method in the application layout template renders the "Login" link for the login page as a hyperlink instead of just text.

The "Login" text/link problem only occurs when redirected to the Login Page via the before_filter machinery, otherwise, the link_to_unless_current method operates as expected.

It seems that link_to_unless_current is using the old page data as the "current" instead of the login page (when redirecting).

A: 

Does your before_filter do a redirect or just render the login page?

ScottD
A: 

Can you show us your link_to_current block? And also, where is login_required redirecting to?

A: 

Appreciate the responses and you can tell by the nature of the question that we're new to rails. By the way, we posted the same question on this site: http://railsforum.com (not sure if it's the official rails forum) with no response yet. StackOverflow so far seems to be creating a great community of helpers willing to reach out to the programmatically challenged.

I think part of the problem is that we were mixing restful urls with standard routes. The login page is mapped to the restful route "/login" but the page redirection was using "/sessions/new" (Rick Olson's restful authentication module)

In application.rb, we forced the filter to "/login" and that solved the problem:

before_filter :login_required

protected

def login_required
  return true if logged_in?
  session[:return_to] = request.request_uri
  flash[:error] = "Please log in first"
  redirect_to "/login" and return false
end

Comments on the technical merits of this approach appreciated as it may be helpful to other newbs.

Thanks, Joe

The only comment I'd make is that "and return false" feels a bit ugly.Given that by that stage, you'll always be returning - you might as well put: redirect_to "/login" falseOtherwise it all looks right to me.
Taryn East
Geh - just looked at my last comment and remembered that comments don't allow formatting... that "false" should be on a newline.
Taryn East
+1  A: 

You can use a route helper method to perform the page redirection:

 redirect_to login_url

If a "named route" for login is defined (which is done by adding an explicit path to "/login" in your "config/routes.rb" file).

This path is actually the same as that generated by:

new_session_url

For a detailed look at routing, I suggest the Rails Routing Guide.

Toby Hede