The basic idea is that:
- You store your latest entry that's been loaded in some way that is accessible to javascript, such as in a
data- attribute
- You loop ajax calls with a delay
- The response of the ajax call will produce changes in your DOM
1
View (images/index.html.erb):
<% render @images %>
View (images/_image.html.erb):
<div class="image" data-id="<%=image.id%>">
<%= image_tag image.image_url(:medium).to_s %>
</div>
2
Javascript:
function poll(){
latest_id = $('div.image:first').data('id')
$.getScript('/images?latest_id='+latest_id)
}
$(function(){setInterval(poll, 5000})
3
Controller:
@images = Image.order('id desc')
@images = @images.where('id > ?', params[:latest_id]) if params[:latest_id]
View (images/index.js.erb):
$('div.image:first').before('<%=j render @images%>').hide().fadeIn()
Note that I've made some assumptions about your model name and paths. You should modify the paths as needed.
This example is for illustrative purposes and is not suitable for real applications - if the server is overloaded, the javascript will keep hammering it with requests, or if your initial page had no initial entries, the way that new entries are inserted will break.