How do I get the devise current_user in javascript

?

In application.rb file declare a before_action function that sets the current_user into a cookie/session (cookie prefered). Then you can access the cookies using “document.cookies” in javascript.

I also found this method on SO but the last line could be simplified by passing from controller current_user.id or current_user.name instead of the entire object

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