How to include js.erb file in view folder

I have a JavaScript file to use with a view. It must have Ruby code in it, and I need to render in Ruby, so I understand that I cannot put a JavaScript file in the asset pipeline. I can put it in the same view folder as the .html.erb file.

How to include a JavaScript file or use this JavaScript file for this view file? I tried javascript_include_tag in my view (obviously using an asset pipeline) using the script src="myfile.js" for the file myfile.js.erb (but it cannot find myfile.js ) and calls my file js.erb users.js.erb ) the same as my .html.erb file ( users.html.erb ), but all to no avail.

+6
source share
2 answers

javascript_include_tag will not work js.erb declared in the view folder itself. There are three different ways to use javascript.

1] Write the code in the view, ie in html.erb itself.

2] Create a js file in the public / javascripts folder and enable it using javascript_include_tag.

3] If you want to make a request like Ajax:

  • Create js.erb in the view folder itself with the same name as the action.
  • In the view where some form is created that will trigger this action, execute the query with :remote => true .
  • In the called action, use the code as follows:

     def action respond_to do |format| format.js end end 
+5
source

you can do it with

 render :partial => "myfile" 

you must save your file in the controller view directory with the name _myfile.js.erb

Now you can write your own code (js, ruby) here and maybe you can highlight js with javascript_include_tag to take advantage of the pipline asset

This file will be displayed first by the erb engine, and then as javascript.

+2
source

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


All Articles