我有以下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