On Thursday, January 9, 2020 at 1:53:52 AM UTC-5, Uzval Mallepeddi wrote: > > 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: >> >> ? >> > 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' endend 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);}); -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/9ec509cd-5b3a-460f-8f96-3de216566589%40googlegroups.com.