4

I have some Javascript to which I need to assign a ruby string. In this case I have some javascript functions written that require logged in users' email address. I am using haml.

In my application layout file (application.html.haml) I could do this and it will work:

%script{:type => "text/javascript", :charset => "utf-8"}
  $(document).ready(function () {
  alert('hello'+ "#{User.find(current_user).email}");
  });

but I have a dedicated js file for my app. application.js file

How Can I pass the logged in user's email address to application.js file from my view??

The following in application.js does not work.

$(document).ready(function () {
  alert('hello' + "#{User.find(current_user).email}");
});
1
  • 2
    As an aside, I would suggest moving queries i.e. User.find(current_user) out of the view and into the controller by setting the result of that query to @current_user - keeps the code base more MVC and in the long run, more readable and manageable. Commented Sep 5, 2011 at 4:20

3 Answers 3

1

You could setup your user information in a global JavaScript variable:

%script{:type => "text/javascript", :charset => "utf-8"}
  var user = { email: "#{escape_javascript User.find(current_user).email}" }
  $(document).ready(function () {
    alert('hello ' + user.email);
  });

and then off in application.js:

$(document).ready(function() {
  alert('hello ' + user.email);
});

And your page should say "hello" twice.

Also, wouldn't current_user normally already be a User instance? If so then current_user.email should be sufficient and if not, then set then you'd want to set @user = ... in your controller and then use @user.email in your view.

I hope I got the HAML right, I don't use it so I'm sort of guessing on the syntax.

Sign up to request clarification or add additional context in comments.

Comments

1

I am assuming that the application.js code is within a function (ie where you need to refer to the current user's email address). IF so, then why not "read" the data/value from a container tag that is not visible to the user? Your view (which is ERB/HAML/etc - just not js - can then write this container tag with the appropriate value evaluated from your model.

Comments

0

You can use gon gem to pass variables from controller to javascript.

Install the gem and setup accordingly, then call gon.current_user_email = current_user.email in the controller.

Then access that string in javascript like gon.variable_name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.