Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1 newbie : where should I put javascript code?

I am developing Rails 3.1 application, I get confused about where should I put my own javascript code(e.g. my.js) and where to put 3rd-party javascript library (e.g. jQuery-UI).

I know in the old version Rails, javascript should all goes into public/javascripts/ directory, when I generate Rails 3.1 app, there is no public/javascripts/ folder, but there is app/assets/ and verndor/assets/ and there is application.js in app/assets, I would like to ask:

  1. in Rails 3.1 ,where should I put my.js and jQuery-UI js in Rails 3.1??
  2. what is the app/assets/application.js supposed to do?
  3. how can I include my.js and jQuery-UI js in my html page?

----------------Am I right?----------

Is require_tree in application.js is used to include 3rd-party libraries under app/vendor/assets/javascript/

and require "something" in application.js is used to include js file under app/assets/javascripts/?? Am I right?

like image 782
Leem.fin Avatar asked Feb 03 '23 12:02

Leem.fin


2 Answers

Put your own javascript & coffeescript under app/assets/javascripts.

Take a look inside app/assets/javascripts/application.js. When you ran rails new APP it should have added //= require_tree . to this file. See section 2.3 for more.

This is a special instruction that Sprockets understands that wil automatically include all files in the same directory as your application.js file and in subfolders below it.

If you want jquery and jquery-ui to be loaded your application.js file should look like

//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require_tree .

If you have gem 'jquery-rails' in your bundle, this gem has already added the jquery files to the asset pipeline for you, so you don't have to worry about downloading them manually.

In your head section of your application view you will want to include javascript_include_tag "application" in the head section. Chances are, if you used the generator, it's already there.

Please read up on the Rails Asset Pipeline for more information.


The . in the line with require_tree is referencing the location of the current file. The //= operator is referencing the asset pipeline.

Placing a file in app/assets, lib/assets or vendor/assets will add it to the asset pipeline. See section 2.1.

like image 187
Alec Wenzowski Avatar answered Feb 09 '23 22:02

Alec Wenzowski


Ryan Bates has a good overview of the asset pipeline on Railscasts. It helped me out when I was trying to sort it out. http://railscasts.com/episodes/279-understanding-the-asset-pipeline

like image 40
Nathan Bailey Avatar answered Feb 09 '23 22:02

Nathan Bailey