Ruby on rails3 where to put javascript code
I'm pretty much a novice to the world of Ruby on Rails, a few weeks back I followed Lynda's good ruby on rails guide so I kinda know how to set up a project etc. Anyway, I made an website in html/css but wanted to do it in rails after all so I went to work. I love ho开发者_StackOverflow社区w you can just "dump" files in folders and rails just picks them out but I also had a few lines of javascript code on my site to "activate" the jquery following. It was in my header
<script type="text/javascript" id="sourcecode">
$(function(){
$('.scroll-pane').jScrollPane({
showArrows: false,
autoReinitialise: true
});
});
</script>
So the simple question now is, where do I put this code since rails doesn't really have an .
Check out this page for layout and rendering: http://guides.rubyonrails.org/layouts_and_rendering.html
There is a section there about rendering your ERB templates. You need to put your javascript code in your .erb template, within the head, just like you would in a normal HTML page.
To be clear, you can save the contents of your script tag into a .js file and link to it in your template, just like you would in plain HTML.
You can place your JS:
- in the erb template it deals with
- under public/javscripts in a normal .js file that you can include in templates using the javascript_include_tag helper
- in seperate .js.erb template files for ajaxian / manual include purposes
EDITED, per suggestion:
Personally, I'd choose one of the last 2 since those are more Convention over Configuration, or the "Rails" way, which is what I believe you're looking for.
I put all scripts in public/javascripts in a directory structure that mirrors controller/action names + a vendor directory and a common directory. In my application.html.* I have code to load what I need for the controller/action into the header. I make a strong effort to not put javascript into my .haml (.erb) files but am willing to break that rule if I must.
I would put them in public/javascripts/
until Rails 3.1.
Also make sure you are including your javascripts in the template.
<% javascript_include_tag :all %>
For loading reasons, don't you want certain javascript snippets to be called after the template loads rather than in the beginning (ex: called in the header)?
精彩评论