How to make Devise respond to both html and json?

橙三吉。 提交于 2021-02-07 20:32:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!