I以下application_controller方法があります。いつbefore_filterとhelper_methodのどちらを使用する必要がありますか?
def current_account
@current_account ||= Account.find_by_subdomain(request.subdomain)
end
私はbefore_filterやhelper_methodを使用して、それを呼び出すれるべきか?両者の違いは何ですか?この場合のトレードオフの観点から私は何を考慮すべきですか?
ありがとうございました。 BETTER CLARITY
FOR
UPDATE私は、ユーザーの代わりに、私は私のビューからコントローラ定義されたメソッドを呼び出すことができるよという点で、helper_method
のbefore_filter
できることを発見しています。多分それはので、ここで、私は私のコードを配置し仕方に何か私が持っているものです。
コントローラ/ 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
このメソッドがコントローラ内で定義されている場合は、** @ current_account **インスタンス変数にアクセスしている場合を除いて、ビューで呼び出すことはできません。 –
@MaurícioLinhares、真実ではない。彼がコントローラ内で 'helper_method:current_account'を呼び出すと、メソッドはビューで利用可能になります。 – tsherif