0

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
Philip7899
  • 4,189
  • 2
  • 44
  • 99
  • Can you just use `$('#user_notifications').prepend("");` to put the newer items at the top of the list instead? And, you would need to pluck the `data('id')` with `first` instead of `last`. – steakchaser Dec 12 '13 at 19:53
  • Thanks, that worked! I understand what prepend does, but why did we need to change last to first? – Philip7899 Dec 12 '13 at 20:07
  • Using `first` gets you the id from the first item in the list (from top to bottom), this way you are getting the id of the most recently added item and then querying for new items against that id. – steakchaser Dec 12 '13 at 21:18

0 Answers0