Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails user 'unseen pages' counter

I have a simple rails app using devise for authentication. I'm interested in creating a counter for each user that updates when they visit certain pages.

For example:

User counter = 4

User visits page A User counter = 3

User visits page A again User counter = 3

User visits page B User counter = 2

I was looking into counter cache that counts # of instances of a model associated with a user, is this somewhat on the right path? Any help would be appreciated. Thanks!

like image 945
Justin Avatar asked Nov 29 '25 03:11

Justin


1 Answers

There are a million ways to skin this cat..... however here is one take.

You'll need to create a PageVisits join model that joins User to Pages, and on that model have counters that you manually increment.

class User < ActiveRecord::Base
  has_many :page_visits
end

class Page < ActiveRecord::Base
  has_many :page_visits
end

class PageVisits < ActiveRecord::Base
  belongs_to :page
  belongs_to :user
end

class CampaignsController < ApplicationController
  def show
    @page = Page.find(params[:id]

    if current_user
      page_visit = @page.page_visits.where(user_id: current_user.id).first_or_create
      page_visit.increment(:visits)
    end

    respond_with(@page)
  end   
end

Like i said, many ways, this is just one SIMPLE way. I'd personally use redis for this kind of task.

like image 89
omarvelous Avatar answered Nov 30 '25 17:11

omarvelous