0

I have many models. Now I like to show the JavaScript to only the particular controller and method.

For example, if I had code like this and want to show it only in communities/show Should I paste this in the head of view/communities/show.html.erb?
or is there smarter way to manage this kind of things? Obviously it looks ugly if I put it in the head of show file because JavaScript always should be placed within < head> tag.

<%= javascript_tag do %>
    jQuery(document).ready(function () {
        refreshPartial();
        setInterval(refreshPartial, 5000)
    });


    function refreshPartial() {
      $.ajax({
        url: "<%= community_path %>/refresh_part",
        type: "GET",
        dataType: "script",
      });
    }
<% end %>
MKK
  • 2,713
  • 5
  • 31
  • 51

2 Answers2

4

communities.js

jQuery(document).ready(function () {
  refreshPartial();
  setInterval(refreshPartial, 5000)
});


function refreshPartial() {
  $.ajax({
    url: "community/refresh_part",
    type: "GET",
    dataType: "script",
  });
}

view/communities/show.html.erb

<%- content_for(:head) do -%>
<%= javascript_include_tag :communities.js -%>
<%- end -%>

communities_layout

<head>
<title>Merry Christmas!</title>
<%= yield(:head) -%>
</head>
Raghvendra Parashar
  • 3,883
  • 1
  • 23
  • 36
  • this is the most cleaner way, and @MKK, you cannot use ruby variables with .js file, but you could use ruby variables will coffscript – sameera207 Dec 29 '12 at 21:01
  • Just changing communities.js to communities.js.coffee will be fine? – MKK Dec 29 '12 at 21:02
  • I have updated it. yes we can use it with coffscript; here we can specify URL as string.. – Raghvendra Parashar Dec 29 '12 at 21:02
  • I already had communities.js.coffee. I think it was automatically created by scaffolding. can I just copy and paste my JS code to there including ruby variable? – MKK Dec 29 '12 at 21:04
1

There are a couple of ways to do that

  1. top of your show.html.erb:

    <% content_for :javascript_includes do %>
    <%= javascript_include_tag "forms.js" %>   
    <% end %>
    

    Also refer to this answer

  2. Where do you put page specific JavaScript code and take a look at How Asset Pipeline works

Community
  • 1
  • 1
Nishant
  • 2,975
  • 23
  • 38