2012-04-06 24 views
2

我有以下application_controller方法:什麼時候應該使用before_filter vs helper_method?

def current_account 
    @current_account ||= Account.find_by_subdomain(request.subdomain) 
    end 

我應該使用的before_filter或者是helper_method來調用它?這兩者之間有什麼區別,在這種情況下我應該考慮哪些方面的權衡?

謝謝。

更新更好的清晰度

我發現我可以用戶before_filter代替helper_method在我能夠從我的觀點呼叫控制器定義的方法。也許它的東西,在我如何安排我的代碼,所以這裏是我:

控制器/ application_controller.rb

class ApplicationController < ActionController::Base 

    protect_from_forgery 

    include SessionsHelper 

    before_filter :current_account 
    helper_method :current_user 

end 

傭工/ sessions_helper.rb

module SessionsHelper 

    private 

    def current_account 
    @current_account ||= Account.find_by_subdomain(request.subdomain) 
    end 

    def current_user 
    @current_user ||= User.find(session[:user_id]) if session[:user_id] 
    end 

    def logged_in? 
    if current_user 
     return true 
    else 
     return false 
    end 
    end 
end 

controllers/spaces_controller.rb

class SpacesController < ApplicationController 

    def home 
    unless logged_in? 
     redirect_to login_path 
    end 
    end 
end 

的意見/空間/ home.html.erb

<%= current_account.inspect %> 

從理論上講,這不應該工作,對不對?

回答

4

使用before_filter或helper_method之間沒有關係。在控制器中有一個想要在視圖中重用的方法時,應該使用助手方法,如果需要在視圖中使用它,則current_account可能是helper_method的一個很好的示例。

+0

我在當前使用此方法的before_filter,並且能夠從我的視圖中調用它。我錯過了什麼嗎? – Nathan 2012-04-06 02:19:37

+1

如果此方法是在控制器內部定義的,則除非您正在訪問** @ current_account **實例變量,否則不可能在視圖中調用它,這是一種不正確的做法。 – 2012-04-06 02:20:33

+0

@MaurícioLinhares,不正確。如果他在控制器中調用'helper_method:current_account',則該方法將在視圖中可用。 – tsherif 2012-04-06 02:26:44

3

他們是兩個完全不同的東西。 A before_filter是你想在行動開始前被稱爲一次。另一方面,輔助方法經常重複,通常在視圖中。

你在那裏的方法就好,保持它的位置。

+0

至於每個非常不同,你是說'helper_method'不會調用每個動作的方法到內存中?換句話說,它只被用作視圖和方法之間的通道,並且從視圖中根據需要調用它? – Nathan 2012-04-06 02:35:39

+0

不,程序員在需要時從視圖(或其他地方)調用helper_method。在控制器操作之前,Rails會自動調用'before_filter's。 – robbrit 2012-04-06 13:57:46

1

我解決了我的問題。我是Rails的新手,並不知道助手目錄中定義的方法是否會自動使用helper_methods。現在我想知道這是如何影響內存/性能。但至少我解開了這個謎。謝謝大家的幫助!

相關問題