I am new to js and started using it with rails. I want to check what variable value is getting passed. I looked on internet and found the we have to use console.log(var_name);' and it gets displayed in console window inbrowser window` (ctrl + shift + j) in firefox. But when checked, nothing is displayed. Below is my code:

customer.js.erb file


But the above is not displaying anything in the console.

Is it the right syntax? And the output is to be displayed in browser window/console or somewhere else?

2 Answers

Amadan On

console.log(...) looks like JavaScript. @customer looks like Ruby. You can't print a Ruby variable in JavaScript - they execute at different times, in different environments. If you're using an EJS file (not JS), then you can do

console.log(<%= @customer.to_json %>)

which will insert the value of Ruby's @customer at the time the JS file is served; but that is very likely not what you want. In almost all cases, you want to either render a Ruby variable inside the HTML, or else to communicate the value of the server variable to the JavaScript code by employing an AJAX request, or render it inside HTML like this:

  var customer = <%= @customer.to_json %>;
Vishal Jariwala On

The right way is something like,


you need to interpolate ruby code in '' or ""