views:

45

answers:

1

Im trying create a live feed block which identifies the latest data added to a forum discussion and automatically updates a block on another page with the latest posts on that forum. Im using Ruby on Rails and I would really appreciate any help on this.

(If my question is not clear I hope I can be more specific with one of these examples). I'm trying to build something like the rolling twitter updates that blogs sites have nowadays or wouldn't mind something like the twitter home page which automatically updates itself. I assume the twitter home page musst using some sort of polling feature.

Any help on how to go about building one of these would be awesome

+2  A: 

These sites do this by regularly polling the server with XmlHttpRequests made by javascript. This is made possible by the setInterval function

The shortest version is something like this (jQuery, but the library translation would be simple):

setInterval(function() {
  $.getJSON('/posts.json', function(posts) {
    // code to remove old posts
    // code to insert new posts
  });
}, 5000);

The 5000 is the time in milliseconds between function-calling.

You would then have your posts controller just return the latest posts:

class PostsController < ApplicationController
  @posts = Post.find(:all, :order => 'created_at desc')

  respond_to do |format|
    format.html
    format.json { render :json => @posts.to_json }
  end
end
Ben
Thanks Ben, Jquery is great. But wont this be too many server requests even if I have 50-60 users logged in at a time? Does the rolling twitter feeds work this way too?
Sid
Well it depends on quite a bit. If its updating every 5 seconds, and a simple DB query, I doubt it. But if you need to squeeze more performance out, consider using Rails Metal: http://railscasts.com/episodes/150-rails-metal
Ben