views:

132

answers:

2

In the profile page of this site StackOverflow, there is an element named "Seen: 2 hours ago" How to implement this in Rails? I googled around but couldn't find the exact piece of code!!

+2  A: 

I should imagine that when you create an account on Stack Overflow your IP address is stored in the database in the Users table. Then when you visit a page on the site, the IP address is retrieved from the HTTP request and the Users table searched for a matching IP address. If there's a match then that user record is updated with a timestamp representing the last visit.

Of course this approach assumes that your site's visitors have a fixed IP address, which may not be the case, particularly for users with a dial-up Internet connection.

You can easily log the current IP address in a Rails model:

class SomeModel < ActiveRecord::Base
  def request=(request)
    self.ip_address = request.remote_ip #ip_address is a string
  end
end

Then in a view helper you can do something like:

def last_seen
  "Seen #{time_ago_in_words(Time.now - some_model.updated_at)} ago"
end

As an alternative, the site could issue a cookie containing a timestamp of the visit which the server would look for. If the cookie was found then the timestamp would be read and the time difference computed. The problem with this approach is that it doesn't work if the user uses a different Web browser or computer (or both).

John Topley
+1  A: 

On the other hand, if your user model has a column named "last_seen_at", you could updated it for every request by a logged in user. Still, i think it would be too heavy on the database...

Authlogic, the awesome plugin for user authentication, will update a magic column for the last time you logged in, which is similar (though not exactly the same) than the "last seen at" you are asking for.

pantulis