Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing current_user variable from application.js in Rails 3

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:

enter image description here

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!

like image 220
David Mauricio Avatar asked Apr 20 '15 00:04

David Mauricio


2 Answers

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);
});
like image 93
David John Smith Avatar answered Nov 14 '22 20:11

David John Smith


  1. Take a look at this episode in rails casts
  2. Try using the gon gem
like image 38
BearGrylls Avatar answered Nov 14 '22 22:11

BearGrylls