Retrieve rails/devise current_user from Backbone

孤街醉人 提交于 2020-01-12 02:05:37

问题


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}"

回答1:


(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}"
  });


来源:https://stackoverflow.com/questions/9582716/retrieve-rails-devise-current-user-from-backbone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!