我有以下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 %>
从理论上讲,这不应该工作,对不对?
我在当前使用此方法的before_filter,并且能够从我的视图中调用它。我错过了什么吗? – Nathan 2012-04-06 02:19:37
如果此方法是在控制器内部定义的,则除非您正在访问** @ current_account **实例变量,否则不可能在视图中调用它,这是一种不正确的做法。 – 2012-04-06 02:20:33
@MaurícioLinhares,不正确。如果他在控制器中调用'helper_method:current_account',则该方法将在视图中可用。 – tsherif 2012-04-06 02:26:44