Wednesday, April 11, 2012

Changing redirect after Devise signin

We use Devise to manage user sign authorization and authentication. This solution offers a lot of stuff for free, such as password resets and account confirmations, but it's also a little hard to navigate at first since most of the functionality seems hidden from view. Read up a little bit though and you'll find just about every customization you desire is written about on the Devise wiki, with instructions on implementation.

Yesterday, I customized the redirect after a user signs in. Initially, devise is set up to redirect to the root_url after sign in, but it's easy enough to override it by adding a after_sign_in_path_for(resource) method in the application controller. Because our signin "page" is actually a small menu that sits on every page, I wanted the user to stay on the current page after signin rather than be redirected to a specific page. For example, if a user is using our map and decides to sign in, I want that user to stay on the map after signin, not be redirected to a different page. Seems easy enough, and although it took me a little while to figure out a solution, the implementation for this functionality isn't all that hard.

The key for me was learning about Rails' request.fullpath, which will return path the user is on. (There is also request.uri, request.url, request.path, request.host and a few others). So, on my sign in form, I added a variable that I set to the fullpath returned from request.fullpath, and passed that variable to the user sign in path as a params. With that, I have the current page the user is on and can redirect them there after successful sign in.

<% current_path = request.fullpath %>
 <%= form_for("user", :url => user_session_path(:current_page => current_url), :html => { :id => "signin_form" }) do |f| %>


application_controller

def after_sign_in_path_for(resource)
 params[:current_page] || super
end


2 comments:

  1. Hello. This is nice that you are learning. But you must know the difference between this Devise program language and PHP. PHP is for web sites while devise is for calculators.

    Also, I don't understand why you have % signs in your code. Is this for you to use as formatting?

    For user sign ins I recommend using PHP and variables with html forms like text and submit.

    If you ever need any help just give me an email at aaron@iwantanewmobilesitebabybaby.com.gov

    ReplyDelete
    Replies
    1. Anonymous3:58 AM

      Dude its not php programming, its Ruby on rails.

      Delete