问题描述
我允许我的用户拥有多个配置文件(用户有多个配置文件),其中一个是默认配置.在我的用户表中,我有一个 default_profile_id.
I'm allowing my users to have multiple profiles (user has many profiles) and one of them is the default. In my users table I have a default_profile_id.
如何创建像 Devise 的 current_user 这样的default_profile",我可以在任何地方使用?
How do I create a "default_profile" like Devise's current_user which I can use everywhere?
我应该把这条线放在哪里?
Where should I put this line?
default_profile = Profile.find(current_user.default_profile_id)
推荐答案
设计的 current_user 方法如下所示:
Devise's current_user method looks like this:
def current_#{mapping}
@current_#{mapping} ||= warden.authenticate(:scope => :#{mapping})
end
如您所见,@current_#{mapping}
正在被记忆.在你的情况下,你想使用这样的东西:
As you can see, the @current_#{mapping}
is being memoized. In your case you'd want to use something like this:
def default_profile
@default_profile ||= Profile.find(current_user.default_profile_id)
end
关于在任何地方使用它,我假设您想在控制器和视图中使用它.如果是这种情况,您可以像这样在 ApplicationController 中声明它:
Regarding using it everywhere, I'm going to assume you want to use it both in your controllers and in your views. If that's the case you would declare it in your ApplicationController like so:
class ApplicationController < ActionController::Base
helper_method :default_profile
def default_profile
@default_profile ||= Profile.find(current_user.default_profile_id)
end
end
helper_method
将允许您在您的视图中访问这个记忆的 default_profile.在 ApplicationController
中使用此方法允许您从其他控制器调用它.
The helper_method
will allow you to access this memoized default_profile in your views. Having this method in the ApplicationController
allows you to call it from your other controllers.
这篇关于创建一个像 Devise 的 current_user 这样的方法到处使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!