How to handle devate authenticate_user! with ajax call?

I have a form with: remote => true, which means it will be submitted via ajax.

In the controller, I have this code:

before_filter: authenticate_user!, :only => [:create] 

I only allow the verified user to create the resource.

However, when authentication fails, devise will raise

 Completed 401 Unauthorized 

and unobtrusive javascript will not be displayed.

But I hope that everything will be like this:

Come up with some posts in flash and make my .js.erb, then I will show Flash to users.

How to do it?

+6
source share
2 answers

This is pretty funny, but the change in devise.rb http_authenticatable_on_xhr to false

 config.http_authenticatable_on_xhr = false 

did the trick for me ... without redefining authenticate_user! Method

Note: I also added: js to navigation formats

 config.navigational_formats = [:"*/*", "*/*", :html, :js] 
+10
source

You need to make your own authenticate_user! and in this action you can have the behavior you want.

 def authenticate_user! unless current_user render 'my_js' end end 
+3
source

Source: https://habr.com/ru/post/911834/


All Articles