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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With