问题
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 ?
回答1:
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
来源:https://stackoverflow.com/questions/32055085/how-to-make-devise-respond-to-both-html-and-json