Rails Devise:获取当前登录用户的对象? [英] Rails Devise: get object of the currently logged in user?

查看:160
本文介绍了Rails Devise:获取当前登录用户的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我在Dev应用程序中安装了Devise,我想知道是否可以在其他模型或控制器中获取当前登录用户的一个实例,如果有的话,我该怎么做

解决方案

Devise创建便捷方法,代表您当前登录的用户。



但是您应该注意到,生成的方法名称包括用户模型的类名。例如如果您的Devise模型被称为'用户',则可以使用' current_user '访问当前登录的用户,如果您的Devise课程是 Admin ,则可以使用' current_admin '访问登录的管理员用户。 p>

有许多其他方法用类似的约定创建,例如' user_signed_in?'或再次' admin_signed_in?',这是非常好的。



这些方法在控制器和视图中可用,因此您可以在查看:

 <%if user_signed_in? %GT; 
< div>以...登录...<%= current_user.email%>< / div>
<%end%>

最后,如果您在应用程序中使用两个或多个Devise模型(例如用户和管理员)您可以使用' anybody_signed_in?'方便的方法来检查这些用户是否已登录:

 <%if anybody_signed_in? %GT; 
< h2>特价优惠< / h2>
< p>所有注册用户将收到免费的猴子!< / p>
<%end%>

更新:



自从Devise版本1.2.0, anybody_signed_in?已被弃用,并被' signed_in?


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?'

这篇关于Rails Devise:获取当前登录用户的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆