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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With