gpt4 book ai didi

ruby-on-rails - 我什么时候应该使用 before_filter 和 helper_method?

转载 作者:行者123 更新时间:2023-12-04 00:09:15 25 4
gpt4 key购买 nike

我有以下 application_controller 方法:

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

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

谢谢。

更新以获得更好的清晰度

我发现我可以使用 before_filter 而不是 helper_method 因为我可以从我的 View 中调用 Controller 定义的方法。也许这是我安排代码的方式,所以这就是我所拥有的:

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 %>

理论上,这应该行不通,对吧?

最佳答案

使用 before_filter 和 helper_method 之间没有关系。当你的 Controller 中有一个方法想要在 View 中重用时,你应该使用 helper 方法,如果你需要在 View 中使用它,这个 current_account 可能是 helper_method 的一个很好的例子。

关于ruby-on-rails - 我什么时候应该使用 before_filter 和 helper_method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10038350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com