开发者

Ruby on Rails & Javascript

I'm fairly new to Ruby on Rails and I'm planing to use a fair amount of javascript in my application. I have done some research but I couldn't find an answer to this one question:

Since you're able to put simple html in all of the views (for example index.html.erb) I was under the assumption that the views basically act as a normal htm开发者_运维知识库l webpage and therefore you should be able to do everything you can do with a normal html webpage. For example put javascript in it from any library you like as long as you include the right doctypes and provide tags for the sources to the libraries as you would in any other html webpage. Is this correct or is there a catch I'm overlooking?

Because I found a lot on the internet about how it's not so simple to use RoR with any javascript library and that you have to take special steps and so forth...

I really would appreciate it if someone could shed some light on this for me. Thanks!


Just point the source place of your javascript files at your layout/application.html.erb file.

e.g: <%= javascript_include_tag :defaults %>.

This will load all the javascript files that are present in your public/javascripts/ directory.

If you need to be more specific you could also put each file separated by a simple comma, like this:

<%= javascript_include_tag 'jquery.js', 'application.js', 'jquery_ujs.js','jquery-ui-1.8.15.custom.min.js' %>

And it's a better approach to put all your javascript code on a file inside that directory.

If it's for general usage you could put the code in the public/javascripts/application.jsfile.

Hope it helps you!


In Rails 3.1, the use of the asset pipeline has changed the way javascript is integrated. JS files no longer need to be copied into the public/javascripts directory and are instead installed as external Gems. A good example is the pjax_rails gem. If you add this to your Gemfile, you will be able to include the pjax javascript into your application layout without the need for running any rake task to copy it over to your public directory.

This helps keep the public directory clean and makes it easier to swap out different JS libraries with minimal fuss.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜