Customize Devise Sing in and Sign up to respond in json

Devise is a popular gem in Rails world for authentication. It gives almost everything for authentication. I mostly use Devise for my most of Rails application.

Apart of all the features provided, I was having trouble getting response of authentication in json format. Although Devise provides flexibility to customize its default features.

I was working on an where I need to authentication via ajax. The application was configured with User is model and Devise is configured upon it. So the entire code you will see will use User model. However you can use any other name you want.

1) Customize Devise Registration Controller to respond in json

File path : [project root]/app/controllers/users/registrations_controller.rb

Code :

 

2) Customize Devise Session Controller to respond in json

File path : [Project root]/app/controllers/users/sessions_controller.rb

Code:

 

3) Modify routes

 devise_for :users, :controllers => {

   :registrations => "users/registrations",
   :sessions => "users/sessions"

   }


Hope that helps!!