Lovish Choudhary
Lovish Choudhary

Reputation: 167

How to make Devise respond to both html and json?

I am overriding the Devise Registrations and Sessions controller to respond to both html and json

Code for Registration Controller :

class RegistrationsController < Devise::RegistrationsController

  def create
    @user = User.create(user_params)
    if @user.save


      render :json => {:state => {:code => 0}, :data => @user }
    else
      render :json => {:state => {:code => 1, :messages => @user.errors.full_messages} }
    end
  end

private

  def user_params
     params.require(:user).permit(:email, :password)
  end
end 

Currently this Registrations controller is only responding to json request. How to make this controller respond to both json and html request ?

Upvotes: 3

Views: 1129

Answers (1)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

You can use a respond_to block to respond to multiple format:

def create
  @user = User.create(user_params)
  respond_to do |format|
    format.html {
      @user.save ? (render @user) : (render :new)
    }
    format.json {
      @user.save ? (render :json => {:state => {:code => 0}, :data => @user }) : render (:json => {:state => {:code => 1, :messages => @user.errors.full_messages} })
    }
  end
end

Upvotes: 4

Related Questions