Create a method like Devise's current_user to use everywhere

旧时模样 提交于 2021-02-07 07:53:40

问题


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.

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)

回答1:


Devise's current_user method looks like this:

def current_#{mapping}
  @current_#{mapping} ||= warden.authenticate(:scope => :#{mapping})
end

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

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

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.




回答2:


You can put this code inside application controller by defining inside a method:

class ApplicationController < ActionController::Base
  ...
  helper_method :default_profile

  def default_profile 
    Profile.find(current_user.default_profile_id)
  rescue
    nil 
  end
  ... 
end

And, can access it like current_user in your application. If you call default_profile, it will give you the profile record if available, otherwise nil.




回答3:


I would add a method profile to user or define a has_one (preferred). Than it is just current_user.profile if you want the default profile:

has_many :profiles
has_one  :profile  # aka the default profile

I would not implement the shortcut method, but you want:

class ApplicationController < ActionController::Base

  def default_profile
    current_user.profile
  end
  helper_method :default_profile

end


来源:https://stackoverflow.com/questions/19194112/create-a-method-like-devises-current-user-to-use-everywhere

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!