0

我在導軌中潛水時遇到以下問題。導軌設計創建自己的sign_in和sign_out動作

所有請求和響應是JSON

後,我在/合作伙伴簽署/ sign_in我得到如下回應:

HTTP/1.1 200 OK { 「成功」:真}

而我退出後/partners/sign_out我得到E採用響應:

HTTP/1.1 200 OK { 「成功」:真正}

現在我的問題: 如何創建我自己的RegisterController以及它如何樣子,還有什麼例子?我在github/devise上搜索過,但沒有找到任何示例。

我想其他響應什麼,如果認證失敗,我要響應HTTP 404錯誤

的routes.rb

devise_for :partners, :controllers => { :sessions => "sessions" } 

session_controller.rb

class SessionsController < Devise::SessionsController 

    def create 
    resource = warden.authenticate!(:scope => resource_name, :recall => :failure) 
    return sign_in_and_redirect(resource_name, resource) 
    end 

    def destroy 
    redirect_path = after_sign_out_path_for(resource_name) 
    signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)) 
    set_flash_message :notice, :signed_out if signed_out 

    respond_to do |format| 
     format.html { redirect_to redirect_path } 
     format.json { render :json => {:success => true} } 
    end 
    end 

    private 

    def sign_in_and_redirect(resource_or_scope, resource=nil) 
    scope = Devise::Mapping.find_scope!(resource_or_scope) 
    resource ||= resource_or_scope 
    sign_in(scope, resource) unless warden.user(scope) == resource 
    return render :json => {:success => true} 
    end 

    def failure 
    return render:json => {:success => false, :errors => ["Login failed."]} 
    end 
end 

回答

1

ActionController的render方法使用hash作爲鍵:status。在這裏,您可以指定該狀態代碼HTTP錯誤狀態代碼或符號:

render json: {success: false, errors: ["Login Failed"]}, status: 404 
# or the following is a preferred way 
render json: {success: false, errors: ["Login Failed"]}, status: :not_found 

這裏render method的文檔。
這裏是由科迪Fauser的優秀文檔rails status code to symbol mapping

一個觀察:

這不是地道在Ruby中使用return語句在函數的結束,因爲最後一個表達式的返回值是返回值的功能。