开发者

Allow an action once per session

I have a site that tracks video views... every time the controller is called. One could flood their own video views with some heavy F5ing.

How to make it so a view counts or a method runs only once per session?

开发者_JAVA百科def show
  new_views = @video.views + 1
  @video.update_attributes(:views => new_views)
end


You can create a session variable, probably upon login, like :

session[:is_logged] = 1

Then, every time you are about to increment the counter, just check this variable.


Single session variable doesn't work because you have many videos and you would like to separate counts for different videos. I think that a better way is to store view events in db.

  • pros: you can even allow action once per user avoiding login/logout
  • cons: huge size of users_videos table


Well the simplest way would be to track it in the session itself:

def show
  if session[:has_counted_view] == nil
    new_views = @video.views + 1
    @video.update_attributes(:views => new_views)
    session[:has_counted_view] = true
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜