Display last visited / seen on profile page?

There is an element named "Seen: 2 hours ago" on the profile page of this StackOverflow site. How to implement this in Rails? I googled around, but could not find the exact code snippet.

+4
source share
2 answers

I have to imagine that when creating an account in Qaru, your IP address is stored in the database in the Users table. Then, when you visit the page on the site, the IP address is retrieved from the HTTP request, and the Users table looks for the corresponding IP address. If there is a match, then this user record is updated with a timestamp representing the last visit.

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

You can easily register the current IP address in the Rails model:

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

Then in the view helper you can do something like:

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

Alternatively, the site may issue a cookie containing the timestamp of the visit that the server will search for. If a cookie was found, the timestamp will be read and the time difference will be calculated. The problem with this approach is that it does not work if the user uses a different web browser or computer (or both).

+2
source

On the other hand, if your user model has a column named "last_seen_at", you can update it for each request by a registered user. However, I think it will be too hard in the database ...

Authlogic, an awesome user authentication plugin, will update the magic column the last time you log in, which is similar (though not quite the same) as the "last seen" you were asking for.

+1
source

Source: https://habr.com/ru/post/1286246/


All Articles