Arrange jQuery Ruby On Rails

Posted on

Question :

I have an app in rails 4 and after doing the scaffolding it generates a * for each template, as I am not yet using coffeescript renamed to * .js and I am trying to use jQuery. The problem is that I need to trigger a process delayed by ajax after loading the page itens/show/x and did as follows

$(document).ready(function() {
    url:'/get_content_recommendation/' + gon.item_id + '.js',

The problem is that it is running on all pages of the app, because of <%= javascript_include_tag "application", media: "all" %> in layout before <%= yield %>

What is the best solution for separating jQuery by view, is there any gem or any good practice? Is this the best way to trigger ajax process after page loading?


Answer :

Rails recommends using Unobtrusive Javascript , where you use selectors to manipulate the elements:

// etc

So one of the ways you can base yourself on a particular element on that page:

<div id="div-especifica-desta-pagina">

And then, via jQuery:

$div_especifica = $("#div-especifica-desta-pagina");
if ($div_especifica.lenght) {

  $.ajax({ ... });


The code inside if will only be executed if the element is found.

An alternative would be to create a Javascript function in NomeDoControlador-NomeDaAção format:

function UsuariosIndex() {

  $.ajax({ ... });


And then call it via a <script> tag only on the correct page:



One alternative is that I use a block in the layout to inject specific files of js, which will only be used in that view, you can use this way:

<% content_for :footer do %>
  <%= javascript_include_tag 'itens_load' %>  
<% end %>

Just that your layout has a <%= yield :footer %> block so you can include the specific js in the block. It’s worth remembering that you should add your specific assets to the precompile of your config/production.rb file, in the example it would be: config.assets.precompile += %w( itens_load.js )


Leave a Reply

Your email address will not be published. Required fields are marked *