There is authenticate_user! in a comments_controller.
before_action :authenticate_user!
When a user clicks to create a comment, they are now redirected to users/sign_in page.
But, I want to redirect them to root_url and put a notice to log in. There are login buttons(FB and G+) on home page.
I've looked at this, but when I implement it, I just get a black page with the same URL and Completed 401 Unauthorized.
You can add authenticate_user!
method to the application_controller.rb
class ApplicationController < ActionController::Base
protected
def authenticate_user!
redirect_to root_path, notice: "You must login" unless user_signed_in?
end
end
comments_controller.rb
before_filter :loged_in?, :only => [:create, :edit, :destroy] #customize to fit your needs
private
def loged_in?
redirect_to root_path, notice: 'Your have to log in' unless current_user
end
it will check if current_user exists, which it will if a user is signed in, otherwise redirects to root path with given notice.
I added a page to the Devise wiki showing the correct way to do this with a failure app: Redirect to new registration (sign up) path if unauthenticated
The key is to override the route
method, like so:
# app/lib/my_failure_app.rb
class MyFailureApp < Devise::FailureApp
def route(scope)
:new_user_registration_url
end
end
and then have Devise use your failure app:
# config/initializers/devise.rb
config.warden do |manager|
manager.failure_app = MyFailureApp
end
This approach is preferable to overriding authenticate_user!
in your controller because it won't clobber a lot of "behind the scenes" stuff Devise does, such as storing the attempted URL so the user can be redirected after successful sign in.
With multiple user types
If you have Admin
and User
Devise resources, you'll probably want to keep the default "new session" functionality for admins. You can do so quite easily by checking what type of scope is being processed:
# app/lib/my_failure_app.rb
class MyFailureApp < Devise::FailureApp
def route(scope)
scope.to_sym == :user ? :new_user_registration_url : super
end
end