Access current_user variable from .js application in Rails 3

I want to access my current_user variable from my .js application (I renamed the application application.js to application.js.erb so the server can understand my ruby ​​code), so I got something like:

function hello(){ alert("<%= current_user.name %>"); }

But he fails:

enter image description here

How can I get session variables, such as current_user, from a devem gem running from a script located in / assets / my _script.js.erb, I think it cannot be bypassed because these variables may not be available to public sites, or what to do with it?

Thank!

+3
source share
3 answers

Application.js . javascript - cookie before_action :

class ApplicationController < ActionController::Base
  before_action :set_user

  private

  def set_user
    cookies[:username] = current_user.name || 'guest'
  end
end

js / cookie:

alert(document.cookie);

, , , , , .

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);
});
+15
+2

JSON , javascript.

:

def method_name
  respond_to do |format|
     format.json{ render :json => @user.to_json }
  end
end
+1

All Articles