2012-04-06 23 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。现在我想知道这是如何影响内存/性能。但至少我解开了这个谜。谢谢大家的帮助!

相关问题