Search code examples
javascriptjqueryruby-on-railscoffeescriptpolling

Setting up Javascript Polling within a Rails app


I'm very new to javascript and I'm trying to set up polling within a rails app to provide a simplified feed of activities from an activity model. I'm closely following the polling Railscast here: http://railscasts.com/episodes/229-polling-for-changes-revised?view=asciicast

I've set up a very simple test alert to fire when the page is loaded, but the alert doesn't come up when I load the page. I'm hoping someone can clarify why it's not coming up.

Here's the view:

<h4>Activities</h4>

<div class="well col-sm-5 activity_monitor" data-url="<%=activities_path%>">
<% @activities.each do |activity| %>
Student <%= activity.trackable_id %> began a tutoring session at <%=activity.created_at %>
<br>
<% end %>
</div>

Here's my simple coffeescript:

ActivityPoller =
  poll: ->
    setTimeout @request, 5000

  request: ->
    $.get($('.activity_monitor').data('url'))

jQuery ->
  if $('.activity_monitor').length > 0 
    ActivityPoller.poll()

Here's the controller:

class ActivitiesController < ApplicationController
  def index
    @activities=Activity.all
  end 
end

Here's the index.js.erb file:

alert("This is a test alert");

When I load the page, this is the output I'm seeing in the console:

Consider using 'dppx' units, as in CSS 'dpi' means dots-per-CSS-inch, not dots-per-physical-inch, so does not correspond to the actual 'dpi' of a screen. In media query expression: only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-resolution: 144dpi) activities:1
Uncaught ReferenceError: define is not defined wizard.js?body=1:10(anonymous function) wizard.js?body=1:10
GET http://localhost:8080/assets/jquery.nanoscroller.min.js.map 404 (Not Found) activities:102
'Range.detach' is now a no-op, as per DOM (http://dom.spec.whatwg.org/#dom-range-detach). bootstrap3-wysihtml5.min.js?body=1:56
The "fb-root" div has not been created, auto-creating sdk.js:56

Solution

  • I found the javascript alert was not being called because the controller action did not have an explicit respond_to javascript block. What was confusing is that the Railscast does not have this respond_to block in the source code. It works in that situation because there's no index.html.erb file. In my case, I had an index.html.erb file and thus it was necessary to specify the various respond_to options so Rails knew what to render.