简体   繁体   中英

Retrieve rails/devise current_user from Backbone

I have an app where I manage the sign up/in/out with Rails through Devise.

When I'm logged in, i'm redirected to Dashboard#index where Backbone start.

I would like to retrieve somehow my current_user.id and current_user.token in Backbone.

My only idea is to have this in my dashboard.html.haml

:javascript
  window.App.current_user.id = "#{current_user.id}"
  window.App.current_user.token = "#{current_user.token}"

(Just beware that only public information should be accesible in the client side)

For a more elegant solution you can create a UserSession Backbone model and fetch it from the server as normal Backbone model.

window.App.UserSession = Backbone.Model.extend({
  urlRoot: "/session"
});

If don't want to make this extra request you can load the model explicitly with data already available in template rendering time:

window.App.current_user = 
  new window.App.UserSession({
    id:    "#{current_user.id}",
    token: "#{current_user.token}"
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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