如何让Devise响应html和json?

时间:2015-08-17 16:14:44

标签: ruby-on-rails devise

我正在重写Devise Registrations和Sessions控制器以响应html和json

注册管理员代码:

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 

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

1 个答案:

答案 0 :(得分:2)

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

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