How to pass ruby ​​string to application.js file in rails

I have Javascript that needs to be assigned a ruby ​​string. In this case, I have some javascript functions that require users to enter the email address. I am using haml.

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

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

but I have a special js file for my application. application.js file

How can I transfer the registered email address of the user to the application.js file from my view?

Below in application.js does not work.

 $(document).ready(function () { alert('hello' + "#{User.find(current_user).email}"); }); 
+4
source share
3 answers

You can customize 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 turn off in application.js :

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

And your page should say hello twice.

Also, usually current_user will not be a user instance? If so, then current_user.email should be enough, and if not, then set that you want to set @user = ... in your controller, and then use @user.email in your view.

I hope I understood HAML correctly, I don’t use it, so I’m kind of guessing the syntax.

+1
source

I assume that the application.js code is inside the function (i.e. where you need to access the user's current email address). IF so, why not “read” the data / value from a container tag that is not displayed to the user? Your view (this is ERB / ​​HAML / etc - just not js) can then write this container tag with the appropriate value evaluated from your model.

+1
source

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

Set the gem and set accordingly, then call gon.current_user_email = current_user.email in the controller.

Then access this line in javascript like gon.variable_name

0
source

All Articles