从Rails 3中的application.js访问current_user变量 [英] Accessing current_user variable from application.js in Rails 3

查看:181
本文介绍了从Rails 3中的application.js访问current_user变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的application.js中访问我的current_user变量(我将我的application.js重命名为application.js.erb,以便服务器可以理解我的ruby代码),所以我得到了一些类似的东西:

  function hello(){alert(<%= current_user.name%>); 

但是失败:



< img src =https://i.stack.imgur.com/fKdEF.pngalt =enter image description here>



我如何获取会话变量像来自devise gem的current_user从位于/assets/my_script.js.erb的脚本工作,我认为不应该被使用,因为这些变量可能不会从公共站点访问,或者应该怎么做?



谢谢!

解决方案

Application.js不会在任何会话变量或方法的上下文中进行评估。从javascript访问用户名的最简单方法是在应用程序控制器上的before_action中设置一个cookie:

  class ApplicationController< ActionController :: Base 
before_action:set_user

private

def set_user
Cookie [:username] = current_user.name || 'guest'
end
end

然后从应用/资产中的任何js您可以访问cookie:

  alert(document.cookie); 

更详细但可以说更清晰的方法是创建一个访问当前用户的路由,并返回用户名例如



routes.rb

  get'current_user'=> users#current_user

users_controller.rb

  def current_user 
render json:{name:current_user.name}
end

application.js

  $。get('/ current_user',function ){
alert(result.name);
});


I wish to access my current_user variable from my application.js (I renamed my application.js to application.js.erb so the server could understand my ruby code), so i got something like:

function hello(){ alert("<%= current_user.name %>"); }

But it fails:

How can i get session variables like the current_user from devise gem working from a script located in /assets/my_script.js.erb, i think it should not be abled because theese variables might not be accesisible from public sites, or what should do about this?

Thanks!

解决方案

Application.js is not evaluated in the context of any session variables or methods. The simplest way to access username from javascript would be to set a cookie in a before_action on application controller:

class ApplicationController < ActionController::Base
  before_action :set_user

  private

  def set_user
    cookies[:username] = current_user.name || 'guest'
  end
end

Then from any js in app/assets you can access the cookie:

alert(document.cookie);

A more verbose but arguably cleaner method would be to create a route that accesses the current user and returns the username e.g.

routes.rb

get 'current_user' => "users#current_user"

users_controller.rb

def current_user
    render json: {name: current_user.name}
end

application.js

$.get('/current_user', function(result){
  alert(result.name);
});

这篇关于从Rails 3中的application.js访问current_user变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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