Is there a way to pass a javascript variable to a ruby ​​method in html.erb

I am trying to pass a variable to a method. Here is an example:

<script>
  var b = 1
  var c = "string" + "<%= method.a(b).to_s%>"
</script>

which does not work.

It works:

<% @b = 1%>
<script>
  var c = "string" + "<%= method.a(@b).to_s%>"
</script>

Any ideas would be appreciated.

+4
source share
4 answers

You cannot evaluate a JavaScript variable inside your Ruby method. In addition, your current script should be outside the asset pipeline, which is usually bad practice.

One simple solution is to pass the variable as a data attribute. You will run your method and then pass the result using jQuery after loading the DOM. This allows you to store JavaScript in the asset pipeline and pass its data evaluated by the Ruby server.

: @b :

<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>

, script JavaScript Rails.

0

gem gon. , :

:

gon.push(variable_name: 1)

js :

gon.variable_name 

: js : .

+1

Ruby , Javascript - .

Ruby, <%= %>, , , Javascript. , - , <% @b = 1 %> HTML- .

, , : Ajax Javascript , , .

0

.

1: . ajax- rails, js.

2: ( ). :

<% @b = 1%>
<script>
   var b = <%= @b %>;
   var c = "string" + "<%= method.a(@b).to_s%>";
</script>

The same value will be available to JS and the server method. But this is not a clean approach. View should not set a value.

And also keep js in the asset pipeline as suggested by @ jeffD23

0
source

Source: https://habr.com/ru/post/1608569/


All Articles