ruby-on-railscachingfragment-caching

Rails fragment caching and timestamp displayed


I'm developing a social network like a mix of Twitter and Facebook based on sports. I have a model called Post (id, user_id, receiver_id, message, created_at) and I want to cache the Post views.

app/views/posts/_post.haml

- cache post do
  %div
    .author= link_to post.user.full_name, post.user
    .message= post.message
    .timestamp= timestamp_for_post(post.created_at)

All worked perfectly yesterday but when I visited my "home feed" I realized that timestamp is cached. Let me show you an example:

Berna Castro
test
Less than a minute ago - Comment  Props  Delete

The thing is it shouldn't display "Less than a minute ago", it should display "Yesterday". Is there any way to don't cache the timestamp? What do you recommend to fix that?

I thought to make an AJAX call for getting the timestamp but that's very weird and not good.


Solution

  • Instead of rendering a relative timestamp, render the actual, non-relative timestamp in your template, and then use something like Moment.js to convert it to a relative timestamp client-side.

    This also has the advantage that the timestamp will update itself if the user has the page open for a long enough period that the relative timestamp would change.

    You should also consider not caching anything until you actually understand what on your site is slow. Caching has a lot of gotchas like this, and prematurely optimization isn’t always worth it.