7

I have a JavaScript file to use with a view. There needs to be Ruby code in it, and I need to do render 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 .html.erb file.

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

3
  • where is your js file and what is your javascript_include_tag looked like? Commented Aug 26, 2013 at 5:40
  • If you want to access the js files outside of the asset pipeline, you have to put in public folder Commented Aug 26, 2013 at 5:40
  • 1
    As an alternative, you can use obtrusive Javascript in layout or page erb file: include <script> tags and use ruby embedded code, but the way you want to include and use .js files is not the rails way. The rails way would be to pass any data between your js side and server's side by data- parameters of html elements. SS=uch approach will result in more cleaner and DRYer code Commented Aug 26, 2013 at 5:45

2 Answers 2

7

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|
        format.js
      end
    end
    
Sign up to request clarification or add additional context in comments.

1 Comment

I'd really appreciate if you put some examples under each step with file names, i.e.: views/model_name/action.js.erb: [code example].
2

you can do this by

render :partial => "myfile"

you have to keep your file in controller's view directory with name _myfile.js.erb

Now you can write your own code (js,ruby) here and probably can separate out js with javascript_include_tag to avail asset pipline

This file will be first rendered by erb engine and then as javascript.

1 Comment

What do you mean by "separate out js with javascript_include_tag to avail asset pipline" ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.