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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With