Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Devise Registration#update via JS in Rails

I'm trying to update the User model through Devise with AJAX and have Devise respond with the proper javascript file.

I want to submit the form remotely to the registrations#update action, but this isn't working with the default response from Devise, which uses the following from the RegistrationsController:

respond_with resource, :location => after_update_path_for(resource)

The above tries to redirect to the default route instead of rendering the update.js.erb file. I am able to overwrite the action and have it work with the following change:

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

But, this seems very brute force as I'm overriding the entire action. Is there a simple way for Devise to know to respond with javascript instead of doing its default redirect?

like image 257
Lev Avatar asked May 02 '13 22:05

Lev


2 Answers

Simply had to add a line to the RegistrationsController so that Devise knows to respond_to both html and js.

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

Reading up on how respond_with really helped. Couple of good links:

Rails API Responder

AsciiCast

like image 174
Lev Avatar answered Nov 13 '22 03:11

Lev


I recently soved this by making the following adjustments, in addition to adding remote: true to the form:

config/initializers/devise:

# 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/registrations/create.js.erb:

alert('success');

views/users/registrations/new.js.erb:

alert('invalid');
like image 31
Brad Werth Avatar answered Nov 13 '22 03:11

Brad Werth