I've recently installed Devise on a rails application, and I am wondering if it is possible to get an instance of the currently logged in user in either one of the other models or controllers, and if so, how do I do that?
Devise creates convenience methods on the fly that represent your currently logged user.
However you should note that the generated method name includes the class name of your user model. e.g. if your Devise model is called 'User
' then the currently logged in user can be accessed with 'current_user
', and if your Devise class is 'Admin
' then the logged in admin user can be accessed with 'current_admin
'.
There are a number of other methods created with similar conventions, for example 'user_signed_in?
' or again 'admin_signed_in?
', which are really nice.
These methods are available in controllers and views so you might have the following in a view:
<% if user_signed_in? %>
<div>Signed in as... <%= current_user.email %></div>
<% end %>
Finally, if you are using two or more Devise models in your app (e.g. User and Admin), you can use the 'anybody_signed_in?
' convenience method to check if either of those types of user are signed in:
<% if anybody_signed_in? %>
<h2>Special offers</h2>
<p>All registered users will receive free monkeys!</p>
<% end %>
Update:
Since Devise version 1.2.0, 'anybody_signed_in?
' has been deprecated and replaced by 'signed_in?
'