我使用devise插件,并有current_user
帮手。我的用户可以在应用程序中拥有多个配置文件,因此用户有has_many :profiles
,并且其中一个配置文件始终处于活动状态。创建current_something帮手
如何以及在哪里可以创建帮手current_profile
?
问候
我使用devise插件,并有current_user
帮手。我的用户可以在应用程序中拥有多个配置文件,因此用户有has_many :profiles
,并且其中一个配置文件始终处于活动状态。创建current_something帮手
如何以及在哪里可以创建帮手current_profile
?
问候
可以在ApplicationController
创建帮助,这将使其可用于从继承的所有控制器和视图:
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_profile
private
def current_profile
# get current_profile based on current_user here
end
end
现在,你可以在任何的意见/控制器使用current_profile
。
至于如何,真的只是找出哪个配置文件是活动的(我假设一个用户在一个给定的会话中只能有1个活动配置文件 - 这将使它更容易)。所以,你所做的就是使用你的会话信息找出当前用户,然后找到活动的个人资料,宾果 - 你就完成了。
只要在哪里,这是一个真正的范围问题。如果你想让辅助方法可用于任何视图,只需在应用程序控制器中声明它,并且你应该很好。
在User
类我想补充的方法
class User
has_many :profiles
def current_profile
@current_profile ||= profiles.where('current = ?', true).first
end
end
,然后你的控制器/助手里面你可以这样写:
current_user.current_profile
希望这有助于。