I’m sort of a noob, so please bear with me!
I’m trying to–when a user is signed in on the dashboard–have jQuery periodically ping the server every X seconds and update the user’s ‘heartbeat’ with the current datetime and set ‘online’ to true.
I’m probably missing some RESTful concepts and concepts involving communication between jQuery and Rails. Just finished Michael Hartl’s Ruby on Rails Tutorial and am building off his sample app.
I’ve done research, but answers mostly involve filling out a form; I want to do this without one.
So I need to somehow pass into jQuery a :user_id and link it to the correct URI. I have a states controller and a states model that belongs_to a user (who has_one of them). Heartbeat and Online are in the states table.
rake routes shows that: PUT /states/:id(.:format) states#update
states_controller.rb
class StatesController < ApplicationController
before_filter :signed_in_user, only: [:thump]
before_filter :correct_user, only: [:thump]
def new
end
def update
@user = User.find(params[:id])
user.update_attributes(heartbeat: Time.now, online: true)
respond_to do |format|
format.js
end
end
end
application.js
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})
// Periodically updates heartbeat
$(function(){
setInterval (thump, 3000);
var js = '<thump> ';
function thump(){
console.log(js + 'Test');
$.ajax({
url: 'states/update',
type: 'POST',
success: function(result) {
console.log(js + result);
}
});
}
});
Thanks for the help.
If the user that you’re trying to perform on is the same as the currently signed on user, it seems like you should ‘t need to pass anything, just use current_user (or whatever) in your controller, instead of passing an id and re-fetching the same object again.