如何让设计同时响应html和json?

时间:2021-07-10 00:06:19

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

我重写设计注册和会话控制器,以响应html和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 ?

目前,这个注册控制器只响应json请求。如何让这个控制器同时响应json和html请求?

1 个解决方案

#1


2  

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

您可以使用respond_to block来响应多种格式:

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

#1


2  

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

您可以使用respond_to block来响应多种格式:

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