I want to use the variables and functions of rails in javascript using erb.

Asked 2 years ago, Updated 2 years ago, 138 views

Cannot access rails functions or variables in app/assets/javascripts/*.js.coffee.erb.
I get scolded for undefined local variable or method.
Specifically, I would like to access the param variable of GET value. Is there a way?

ruby-on-rails erb

2022-09-30 19:33

2 Answers

If you want to pass the value from Rails to javascript, you can write it in the view file as follows.

<%=javascript_tag do%>
    window.hoge='<%=j@hoge%>';
    window.fuga='<%=j params[:fuga]||"Default value"%>;;

    alert(hoge);
    alert(fuga);
<%end%>

You can also use a gem called gon.

Reference Site
http://ja.asciicasts.com/episodes/324-passing-data-to-javascript
http://qiita.com/mosa_siru/items/e69eee47a183b13cfb62
http://qiita.com/yk-212/items/8d648b83e24a43af17ba


2022-09-30 19:33

I don't have any.

erb only processes eRuby scripts and
AssetPipeline is for compression through compilation, binding, etc.
The GET query (params variable) does not change the code in the output.
http://railsdoc.com/asset_pipeline
(if it is done.What happens to pre-compiled ones?)

If such action is required,
For those views, I prepared the original .js.erb and
It can be implemented by calling a query string from a script tag.


2022-09-30 19:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.