0

I am making a rails5 blog app with devise. In the comments controller, I check if the user exists using "before_action :authenticate_user!".

So, if the user is logged in then create comment method gets executed and the server response gets send back to the client via AJAX. However, if the user is not logged in then "before_action :authenticate_user!" check creates a 401 authentication error in the response ( can be seen in the browser log).

I want to just display the flash message just above the comment box or somewhere on the page so that user knows that he/she can not enter a comment without logged in.

There are many similar questions I have found but they seem very confusing and none of the solutions worked for me. Most of them talk about the changing the devise confg (e.g. config.http_authenticatable_on_xhr = false) or override the authenticate_user method etc.

Can someone just explain is it possible to show a flash message warning to the user to login to add comment (ajax call). I don't want automatic redirect for AJAX calls.

1 Answer 1

1

Create a flash method then catch the unauthorized error in jQuery and show your flash message :

@flash = (content, type) ->
  content = "<div class='container'><div class=\"alert alert-#{type}\">#{content}</div></div>" if type?
  $('#flash').clearQueue().hide().html(content).fadeIn('slow').delay(3000).fadeOut('slow')

$(document).ajaxError (e, xhr, settings) ->
  flash("Unauthorized", "danger") if xhr.status == 401
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.