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

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>

Leave a Comment