Ordering polling requests

72 views Asked by At

I am trying to follow rails casts episode #228 on polling for changes. I am essentially following the screencast word for word, except that I am using it for notifications instead of comments. The only difference is that every time he uses the word 'comment', i use the word 'user_notification'. Every time he uses the word 'comments', I use 'user_notifications'. Also, in the screencast comments belongs_to articles, whereas in my app user_notifications belongs_to user, so I replace the word 'article' with 'current_user'. I was able to setup the user_notifications successfully, except for that the newest notifications appear at the bottom. I fixed this by adding a .order to user_notifications in the show.html.erb file (see below). The problem is that since the javascript is telling it to poll for all user_notifications with an 'id > params[:after]' (see the index action in the controller below), it re-appends the user_notifications with a higher id since the order was reversed. How do I fix this?

Here is my code:

user_notifications.js.coffee

@UserNotificationPoller =
  poll: ->
    setTimeout @request, 5000

  request: ->
    $.get($('#user_notifications').data('url'), after: $('.user_notification').last().data('id'))

jQuery ->
  UserNotificationPoller.poll()

show.html.erb

<%= content_tag :div, id: "user_notifications", data: {url: user_notifications_url} do %>
    <%= render current_user.user_notifications.order(created_at: :desc) %>
<% end %>

index.js.erb

$('#user_notifications').append("<%= j render(@user_notifications) %>");
UserNotificationPoller.poll()

user_notifications_controller:

def index
    @user_notifications = current_user.user_notifications.where('id > ?', params[:after].to_i)
end
0

There are 0 answers