Aen*_*Tan 3 ruby methods ruby-on-rails
我让我的用户有多个配置文件(用户有很多的配置文件),其中一个是默认的.在我的users表中,我有一个default_profile_id.
如何创建一个"DEFAULT_PROFILE的"像设计的CURRENT_USER,我可以到处使用?
我应该把这条线放在哪里?
default_profile = Profile.find(current_user.default_profile_id)
Run Code Online (Sandbox Code Playgroud)
Devise的current_user方法如下所示:
def current_#{mapping}
@current_#{mapping} ||= warden.authenticate(:scope => :#{mapping})
end
Run Code Online (Sandbox Code Playgroud)
如你所见,@current_#{mapping}正在被记忆.在你的情况下,你想要使用这样的东西:
def default_profile
@default_profile ||= Profile.find(current_user.default_profile_id)
end
Run Code Online (Sandbox Code Playgroud)
关于在任何地方使用它,我将假设您想在控制器和视图中使用它.如果是这种情况,您可以在ApplicationController中声明它,如下所示:
class ApplicationController < ActionController::Base
helper_method :default_profile
def default_profile
@default_profile ||= Profile.find(current_user.default_profile_id)
end
end
Run Code Online (Sandbox Code Playgroud)
这helper_method将允许您在视图中访问此memoized default_profile.在此方法中ApplicationController允许您从其他控制器中调用它.
| 归档时间: |
|
| 查看次数: |
1491 次 |
| 最近记录: |