Question: Rails devise before_filter authenticate_user! guide to sign up path instead of sign in path


Rails devise before_filter authenticate_user! guide to sign up path instead of sign in path

Answers 2
Added at 2016-12-28 19:12

I'm using Rails devise. Applying before_filter authenticate_user! to a controller is pretty magical and almost offers the exact redirect solution I am looking for. However!-- I'd prefer that when clicking a link blocked by authenticate_user!, the user be redirect to the new_user_registration_path (sign up), instead of the new_user_session_path (sign in).

Is there a way to easily customize devise to allow for this?

nr: #1 dodano: 2016-12-28 20:12


We can use store_location_for which stores the provided location to redirect the user after signing in.

In your application_controller.rb add


def authenticate_user!
    unless user_signed_in?
    store_location_for(:user, request.url)
    redirect_to new_user_registration_url

And in your controller you can add:

before_action :authenticate_user!, :unless => :devise_controller? #   This prevent the infinite redirects.

This code above will do the trick for specific controller as you mentioned in your question, and redirect user to sign up page instead of login page. If you would like to use only on certain links in your view you can check the code I posted below EDIT.


You can simple check if !current_user and when user click on the link, it will be redirected to sign up page. This code below will return user to the previous page for sure. You can put the code below to your views, and use if else as well:

<% if !current_user %>
  <%= link_to 'Register', new_user_registration_path %>
<% end %>

NOTE before_filter syntax is deprecated in Rails 5.0 and will be removed in Rails 5.1

nr: #2 dodano: 2016-12-28 20:12

In your application_controller.rb file:

before_filter :authenticate_user

def authenticate_user
  redirect_to new_user_registration_url unless user_signed_in?
Source Show
◀ Wstecz