Search code examples
ruby-on-railsdevise

How to redirect back to a link after logged in


My application has a function, if a user saved a comment, an email with a link will be sent and if a link is clicked, a comment is opened, if the user already logged-in. If user didn't log-in yet, then a log-in page is opened.

But I don't know how can I write the code for the redirection to comment page(link) after logged-in...

Means:

If user logged-in => click the link => comment page opened (working)

If user not logged-in => log-in page opened => user logged-in (till here working) => comment page(link) opened (not working). Currently a message was shown "You need to log in or sign up before continuing." but no log-in page is opened.

If I change the link <%= link_to 'Go to this project', ranks_url %>, then I can open the log-in page and after that the correct page.

<%= link_to 'Go to your comment', registered_comments_url(@comment) %>

comments_controller

before_action :store_user_location!, if: :storable_location?
  before_action :authenticate_user!
  def storable_location?
    request.get? && is_navigational_format? && !devise_controller? && !request.xhr?
  end

  def store_user_location!
      # :user is the scope we are authenticating
    store_location_for(:user, request.fullpath)
  end

  def after_sign_in_path_for(resource_or_scope)
    stored_location_for(resource_or_scope) || super
  end

Can someone help me?


Solution

  • If you use "is_navigational_format?" like below,

    def storable_location?
          request.get? && is_navigational_format? && !devise_controller? && !request.xhr?
        end
    

    and if you have a link with id like "/comments/anytask.123", then "is_navigational_format?" can not judge ".123" as a format.

    So I needed to add below routes and solved!!!

    get 'comments/anytask.:id' => 'comments#anytask', as: :comments_anytask