从Rails 3中的application.js访问current_user变量 [英] Accessing current_user variable from application.js in Rails 3
问题描述
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屋!