简体   繁体   中英

Javascript files in Rails 3.1 Asset Pipeline

I've tested my Rails app's functionality by placing jQuery at the bottom of my home.html.erb file with simple script tags. Everything works fine until I attempt to utilize the Asset Pipleine in Rails 3.1 and place the script within app/javascripts/home.js.erb

Anyone know why I can't get the javascript to work outside of the home.html.erb file

you could add the script tag in the application.html.erb and you'll have jquery in all your pages. you can add the script in this way: (you should add the jquery-1.7.min file in the folder app/javascript)

    <%= javascript_include_tag 'jquery-1.7.min'%> 

Don't put home.js.erb in app/javascripts but extract your jquery from home.js.erb and put in app/assets/javascripts/home.js

add config.assets.precompile += %w( *.js ) to config/environments/production.rb or in config/application.rb for global env (test/dev/prod)

than in app/assets/javascripts/application.js have

//= require jquery
//= require jquery_ujs
//= require_self
//= require_tree .

call it with javascript_include_tag "application" from the view

... and finally, don't forget to add gem 'jquery-rails' to your Gemfile and run bundle

As far as what I was looking to do, which was separate javascript files for different views, I was unsuccessful. I tried different naming conventions, etc.

What has worked for me however, is putting all of my javascript within application.js . Doing this makes this code accessible by every view throughout the entire application. Depending upon your needs and your app, you may want to put the script within [your-model-name].js.coffee which will make it accessible (I think just for your particular controllers and views). Since my app is a single model/controller setup, this is essentially the same thing.

Then, it's a matter of using selectors carefully as to not interfere with other pages unintentionally. In other words, if you want a piece of code to run within one particular view and not another, you will have to adjust your .js code accordingly, since everything within application.js is accessible to all views.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM