Best way to add page specific JavaScript in a Rails 3 app?

Brian Armstrong picture Brian Armstrong · Aug 9, 2010 · Viewed 84.8k times · Source

Rails 3 has some unobtrusive JavaScript which is pretty cool.

But I was wondering what the best way is to include additional JavaScript for a particular page.

For example, where I might have previously done:

<%= f.radio_button :rating, 'positive', :onclick => "$('some_div').show();" %>

We can now make it unobtrusive with something like

<%= f.radio_button :rating, 'positive' %>

# then in some other file
$('user_rating_positive').click(function() {
  $('some_div').show();
}

So I guess my question is where/how to include that JavaScript? I don’t want to fill up the application.js file because this JavaScript is only applicable to this one view. Should I include a custom JavaScript file for each page somehow, or stick it in an instance variable that the header looks for?

Answer

bjg picture bjg · Aug 9, 2010

What I like to do is include the per-view Javascript in a content_for :head block and then yield to that block in your application layout. For example

If it's pretty short then:

<% content_for :head do %>
  <script type="text/javascript">
    $(function() {
      $('user_rating_positve').click(function() {
        $('some_div').show();
      }
    });
  </script>
<% end %>

or, if longer, then:

<% content_for :head do %>
  <script type="text/javascript">
    <%= render :partial => "my_view_javascript"
  </script>
<% end %>

Then, in your layout file

<head>
  ...
  <%= yield :head %>
</head>