I'm trying to pass a variable into a method. Here is an example:
<script>
var b = 1
var c = "string" + "<%= method.a(b).to_s%>"
</script>
which doesn't work.
This works:
<% @b = 1%>
<script>
var c = "string" + "<%= method.a(@b).to_s%>"
</script>
Any ideas would be appreciated.
You can't evaluate a JavaScript variable inside your Ruby method. Also, your current script has to be outside the asset pipeline, which is usually a bad practice.
One simple solution is to pass the variable as a data attribute. You would run your method, then pass the result with jQuery after the DOM has loaded. This allows you to keep JavaScript in the asset pipeline and pass it data evaluated by Ruby server-side.
Note: @b
should be defined on your controller:
<div id="foo" data-bar="<%= method.a(@b).to_s %>"></div>
<script>
$(document).ready(function() {
var b = $(#foo).data('bar');
var c = "string" + b;
});
</script>
The other option is to render your script asynchronously with unobtrusive JavaScript in Rails.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With