2017-07-25 31 views
1

我應該在過濾器之前加載並檢查數據庫源的存在嗎?什麼樣的邏輯應該在Rails之前過濾器

在我們的應用程序中,我們總是加載並檢查具有由params傳入的id的DB源的存在。我不確定這是否是一個好的模式。

喜歡:

before_action :set_org 

private 

def seg_org 
    @org ||= Organization.find params[:id] 
    resource_not_found unless @org 
end 
+0

不['find'(http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods。 html#method-i-find)已經引發錯誤?在這種情況下,你的'resource_not_found'根本不會被執行。所以最好刪除它。 – vee

+1

這實際上是如何[rails scaffold generator](https://github.com/rails/rails/blob/master/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb)設置控制器默認情況下(第7和55行)。所以這是一個相當不錯的標誌,如果沒有別的東西,這不是一個可怕的想法或做事的方式 –

+0

@vee'find'不會產生任何錯誤。如果沒有發現,它將返回'nil'。 – hiveer

回答

0

是,找到一個記錄並將其設置爲一個實例變量是用於控制器的過濾器的常用約定。一般來說,任何可以運行多個操作的代碼都是很好的選擇。說你要重定向到登錄頁面,如果當前用戶沒有登錄。

class UsersController < ApplicationController 
    before_action :require_login 
    before_action :set_user, only: [:show, :edit, :update, :destroy] 

    private 

    def require_login 
    unless logged_in? 
     flash[:error] = "You must be logged in to access this section" 
     redirect_to new_login_url # halts request cycle 
    end 
    end 

    def set_user 
    @user = User.find(params[:id]) 
    end 
end 
+0

爲什麼這是downvoted? –

+0

我不知道是誰做的。 :) 任何方式,我投你回來。 – hiveer

+0

@hiveer lol thanks:)當某些事情被拒絕投票時,我們很高興得到一個評論,所以可以改進。我覺得這是一個合理的答案,所以我只是困惑。這個答案有幫助嗎? –