Reputation: 1197
I use devise plugin and there is current_user
helper. My users can have many profiles in application so User have has_many :profiles
and always one of them is active.
How, and where can I create helper current_profile
?
Regards
Upvotes: 2
Views: 98
Reputation: 50057
In the User
class I would add a method
class User
has_many :profiles
def current_profile
@current_profile ||= profiles.where('current = ?', true).first
end
end
and then inside your controller/helpers you could just write:
current_user.current_profile
Hope this helps.
Upvotes: 1
Reputation: 33954
As far as how, is really just a matter of figuring out which profile is active (I'm assuming that a user can ONLY have 1 active profile in a given session - that will make it easier). So, what you do is use your session info to find out the current user, then find the active profile, and bingo - you're done.
As far as where, that's really a question of scope. If you want to have the helper method available to any view, simply declare it in the application controller, and you should be good.
Upvotes: 0
Reputation: 20645
You can create the helper in ApplicationController
, which will make it available to all controllers and views that inherit from it:
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_profile
private
def current_profile
# get current_profile based on current_user here
end
end
Now you can use current_profile
in any views/controllers.
Upvotes: 4