I’ve worked through Ruby on Rails Tutorial by Michael Hartl, and have also implemented a small login form included on the navbar of my application (so a user can either login from the actual login page or from the navbar login). If a user logs in from the login page, I do want them to be redireced to the root_url.
However, if the user logs in from the navbar form, I want them to stay on the same page with a “Successfully logged in!” message at the top of the page. How can I do this?
My code is as follows:
From the _header.html.erb file:
<%= form_tag sessions_path, class: "navbar-form pull-right" do %>
<%= text_field_tag :email, nil, class: "input-small", placeholder: "Email" %>
<%= password_field_tag :password, nil, class: "input-small", placeholder: "Password" %>
<%= check_box_tag :remember_me, 1, params[:remember_me], title: "select to remember login" %>
<%= submit_tag "Sign in", class: "btn btn-mini" %>
<% end %>
From the sessions_helper.rb file:
def redirect_back_or(default)
redirect_to(session[:return_to] || default)
session.delete(:return_to)
end
def store_location
session[:return_to] = request.url
end
I have tried to leverage the redirect_back_or method from the sessions_helper.rb, but it seems to be capturing a session path as the session[:return_to] value, rather than the originating page for the login request. I would appreciate your ideas.
I was finally able to figure this out…
In my
sessions_helper.rbfile (which is already included in theApplicationController), I add the following code:Then I changed my
SessionsControllercreate action to read:These changes result in the desired behavior:
I’m guessing this could be refactored some, but it works.