Gregir Gregir - 3 years ago 153
Ruby Question

How to include js.erb file in view folder

I have a JavaScript file to use with a view. There needs to be Ruby code in it, and I need to do

in Ruby, so I understand that I can't put the JavaScript file in the asset pipeline. I can put it in the same view folder as the

How do I include the JavaScript file, or use that JavaScript file for that view file? I tried
in my view (that uses the asset pipeline apparently), using script
for the
file (but it can't find
), and names my
file (
) the same as my
file (
), but all to no avail.

Answer Source

javascript_include_tag won't work js.erb declared in the view folder itself. There are three different ways you can have the javascript.

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

2] Create js file in public/javascripts folder and include it using javascript_include_tag.

3] In case you want to make the request as Ajax:

  • Create the js.erb in the view folder itself with the same name as that of the action.
  • In the view where some form is created which will be calling this action, make the request using :remote => true.
  • In the called action, use code as follows:

    def action
      respond_to do |format|
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download