Showing if someone is reading a post

夙愿已清 提交于 2020-01-06 18:04:10

问题


I want to show the list of people who are reading a post. Before attempting to implement the function, I wanted to ask for some advice. I would start by checking users who invoke the show action in the PostsController; every time a person views a post, he will be recorded onto the list of people who are reading the post. However, I am not sure how to remove the person from the list when he navigates away from reading the post. Is there a way to use cookies or sessions to notice if the user navigates away from a certain page? A little bit of help would help me get started right away!

I appreciate any advice. Thank you!


回答1:


To be more accurate

in routes.rb

post "/posts/:id/being_read" => "posts#being_read", :defaults => { :format => "json"}

in controller

PostsController < ApplicationController
  def being_read
    current_user && @post.being_read_by current_user
    head :ok
  end
end

on show page

function beingRead(){
  $.post("/posts/<%=@post.id%>/being_read", function(data) {
    setTimeout(beingRead,10000);
  });
}

in post.rb

def being_read_by user=nil
  # making use of rails low level cache

  readers_ids = Rails.cache.fetch("Post #{id} being read", :expires_in => 5.minutes) || []

  readers_ids = Rails.cache.fetch("Post #{id} being read", :expires_in => 5.minutes) (readers_ids << user.id) if user

  readers_ids
end



回答2:


Usually, a system of timeout is used.

Rather than store a boolean "is reading post", we can store the date on which the user has read the post.

No, you can easily set a timeout (for example 5 minutes) to know who are reading the post. This is an approximation, but this is almost realistic.

Advantages :

  • you can delete the finished dates when you want (with a cron, each day, or something else), with a single query rather than one a each view.
  • you resolve the problem of the user who close its browser (when no next page is open)


来源:https://stackoverflow.com/questions/15830212/showing-if-someone-is-reading-a-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!