简体   繁体   English

如何从Devise in Rails中获取current_user以供JS使用

[英]How can I get the current_user from Devise in Rails for JS use

I'm trying to figure out the best way to get the current_users username and id from devise in rails without having to store it in the DOM for later access. 我正在尝试找出从rails中的dev中获取current_users用户名和ID的最佳方法,而不必将其存储在DOM中以供以后访问。 Are there any techniques/strategies to accomplish this? 是否有任何技术/策略可以做到这一点?

While Rails is just the backend on your server and javascript is the frontend on client-side you defenitely need to put something inside html or ajax it. 尽管Rails只是服务器的后端,而javascript是客户端的前端,但是您绝对需要在html或ajax内放置一些内容。

a few approaches: 一些方法:

1. just write it into the body with an data attribute 1.用数据属性将其写入主体

<body data-username="<%= current_user.username %>

2. making an ajax call to the server to receive that information (pseudocode) 2.对服务器进行ajax调用以接收该信息(伪代码)

$.ready() {
  $.getJSON(/api/user-information, function(data) {
    username = data.username
    settings = data.settings
    unread_messages = data.unread_messages_count
  }
}
# /api/user-information
def user_info
  render json: {username: current_user.name, settings: {enabled: false, wants_chat: true}, unread_messages: 10}
end

or 3. maybe this gem is helping you https://github.com/kbparagua/paloma 3.也许这颗宝石在帮助您https://github.com/kbparagua/paloma

if you need that information to make some ajax-calls on certain urls or whatever - i always would go with solution #1. 如果您需要该信息来对某些URL或其他内容进行Ajax调用-我总是会选择解决方案1。 thats why data-attributes exist in HTML5 那就是为什么HTML5中存在数据属性的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM