3

我有以下 application_controller 方法:

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

我应该使用 before_filter 还是 helper_method 来调用它?两者之间有什么区别,在这种情况下我应该考虑什么权衡?

谢谢。

更新以获得更好的清晰度

我发现我可以使用 thebefore_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

控制器/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

3 回答 3

4

使用 before_filter 或 helper_method 之间没有关系。当你的控制器中有一个方法想要在视图中重用时,你应该使用辅助方法,如果你需要在视图中使用它,这个 current_account 可能是 helper_method 的一个很好的例子。

于 2012-04-06T02:13:41.213 回答
3

它们是两个非常不同的东西。Abefore_filter是您希望在操作开始之前调用一次的东西。另一方面,辅助方法经常重复,通常在视图中。

您拥有的那种方法可以留在原地。

于 2012-04-06T02:14:09.130 回答
1

我解决了我的问题。我是 Rails 新手,不知道 helpers 目录中定义的方法自动是 helper_methods。现在我想知道这如何影响内存/性能。但至少我解开了这个谜。感谢大家的帮助!

于 2012-04-06T03:10:58.300 回答