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 %>

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

4 Comments

this is the most cleaner way, and @MKK, you cannot use ruby variables with .js file, but you could use ruby variables will coffscript
Just changing communities.js to communities.js.coffee will be fine?
I have updated it. yes we can use it with coffscript; here we can specify URL as string..
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?
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.