何时应该使用before_filter而不是helper_method?

3

我有下面的application_controller方法:

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

我应该使用before_filter还是helper_method来调用它?两者之间有什么区别,我在这种情况下应该考虑哪些权衡?谢谢。
为了更好的清晰度更新:
我发现我可以使用before_filter而不是helper_method,因为我能够从视图中调用控制器定义的方法。也许是我的代码编写方式有问题,所以这是我的代码:
controllers/application_controller.rb
class ApplicationController < ActionController::Base

  protect_from_forgery

  include SessionsHelper

  before_filter :current_account
  helper_method :current_user

end

helpers/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

views/spaces/home.html.erb

<%= current_account.inspect %>

在理论上,这不应该起作用,对吧?
3个回答

4

使用before_filter或helper_method没有关系。当您在控制器中有一个方法希望在视图中重复使用时,应该使用helper_method,例如current_account可以作为helper_method的好例子,如果您需要在视图中使用它。


我目前在这个方法上使用了一个before_filter,并且能够从我的视图中调用它。我有什么遗漏吗? - Nathan
1
如果这个方法是在控制器内定义的,你不可能在视图中调用它,除非你正在访问 @current_account 实例变量,这将是一种不好的做法。 - Maurício Linhares
@MaurícioLinhares,不是这样的。如果他在控制器中调用helper_method :current_account,那么该方法将在视图中可用。 - tsherif
我发布了我的代码...也许这会有所帮助。请注意,我在application_controller中使用了before_filter - Nathan
@Nathan,你在SessionsHelper中定义了current_account,默认情况下视图可以使用它。然后你通过在ApplicationController中包含SessionsHelper,使其对所有控制器可用。 - James
显示剩余3条评论

3
他们是两个非常不同的东西。一个before_filter是在动作开始之前你想要被调用一次的东西。另一方面,助手方法会经常重复使用,通常在视图中使用。
那个方法你现在有的位置就可以了。

每个方法都非常不同,你是说 helper_method 不会为每个操作将方法调用到内存中吗?换句话说,它只是在视图和方法之间起到一个通道的作用,并且根据需要从视图中调用? - Nathan
不,程序员在需要时从视图(或其他地方)调用helper_method。Rails会自动在控制器操作之前调用before_filter - robbrit

1

我解决了我的问题。我是Rails的新手,不知道在helpers目录中定义的方法会自动成为helper_methods。现在我想知道这对内存/性能有什么影响。但至少我已经解决了这个谜团。感谢大家的帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接