Update # registration using JS in Rails

I am trying to update the User model through Devise using AJAX and let Devise respond with the appropriate javascript file.

I want to submit the form remotely to the # update registration action, but this does not work with the default response from Devise, which uses the following from RegistrationsController:

respond_with resource, :location => after_update_path_for(resource) 

The above attempt to redirect to the default route instead of rendering the update.js.erb file. I can overwrite the action and make it work with the following change:

 respond_to do |format| format.html format.js end 

But this seems like very brute force as I redefine the whole action. Is there an easy way for Devise to learn how to respond with javascript and not do the default redirection?

+7
source share
2 answers

It was just necessary to add a line to the RegistrationsController so that Devise knew that it needed to respond to both html and js.

 class RegistrationsController < Devise::RegistrationsController respond_to :html, :js end 

Reading how response_with really helped. A couple of good links:

Rails API Responder

Asciicast

+11
source

I recently took this, making the following changes, in addition to adding remote: true to the form:

config / Initializers / Develop

 # If http headers should be returned for AJAX requests. True by default. config.http_authenticatable_on_xhr = false 

config /routes.rb

 devise_for :users, controllers: { registrations: 'users/registrations' } 

Controllers / Users / registrations_controller.rb

 class Users::RegistrationsController < Devise::RegistrationsController respond_to :html, :js end 

views / users / registration / create.js.erb

 alert('success'); 

views / users / registration / new.js.erb

 alert('invalid'); 
+2
source

All Articles