Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a method like Devise's current_user to use everywhere

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)
like image 698
Aen Tan Avatar asked Dec 11 '22 10:12

Aen Tan


1 Answers

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.

like image 134
AdamT Avatar answered Jan 05 '23 01:01

AdamT