I found a number of questions and answers regarding updating a partial using Ajax after submitting a form. But my question is ?simpler?, I just want to reload a partial ever
Well it turns out the answer is a little complicated:
Step 1: Use Javascript's setInterval
function along with jQuery's $.get()
function to load a page, say /users/1/posts/latest
.
setInterval(function(){
$.get("/users/1/posts/latest.js", function(data){
$("latest_post").html(data);
},
"html")
}, 30000);
Step 2: Create a latest.js.erb
and put it in your app/views/posts
folder.
Contents of latest.js.erb
:
<%= render partial: 'posts/latest', object: @user.posts.last, as: :post %>
Step 3: Create the above partial with whatever you'd like (if you don't need a partial, you can just write the entire contents of the div in the latest.js.erb
file.)
Step 4: Add a latest method to your PostsController
, that defines @user
, etc. for the latest.js.erb
to use.
Step 5: Add get '/latest'
to your routes.rb