How do I get the devise current_user in javascript

23 views
Skip to first unread message

fugee ohu

unread,
Jan 8, 2020, 10:13:44 PM1/8/20
to Ruby on Rails: Talk
?

Uzval Mallepeddi

unread,
Jan 9, 2020, 1:53:52 AM1/9/20
to Ruby on Rails: Talk
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.

On Wednesday, January 8, 2020 at 10:13:44 PM UTC-5, fugee ohu wrote:
?

fugee ohu

unread,
Jan 9, 2020, 6:19:58 AM1/9/20
to Ruby on Rails: Talk
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);
});
Reply all
Reply to author
Forward
0 new messages