Loenvpy
Loenvpy

Reputation: 919

Count users who had viewed a specific page in rails

How can I implement the same feature as Linkedin (count users who has viewed my profile page) for my rails app, so users will get notified for users who has viewed their profile?

Upvotes: 0

Views: 356

Answers (2)

Rafa Paez
Rafa Paez

Reputation: 4860

First of all you need to define your Visit model. It will have at least the following attributes:

  • id (visit id)
  • user_id (id of the visitor)
  • page_url (the page visited)
  • created_at (date and time of the visit)

Then you can decide to store it in a Relationa Database like MySQL or in a NO-SQL one like MongoDB. For this case any of them it could be a good option.

If you decide the SQL solution, just add a has_many :visits in your User model and :belongs_to :user in your Visit model.

And that's a good point to start from.

Upvotes: 1

Maksim Gladkov
Maksim Gladkov

Reputation: 3079

You should add a new model, e.g.:

class PageView
    belongs_to :page
    belongs_to :user
end

Use it like this:

PageView.create(page: @page, user: current_user) # to register page view
PageView.where(page: @page).count # to get views count for particular page
PageView.where(page: @page, created_at: 1.week.ago..Time.now) # to get views count for particular page for a week

Upvotes: 1

Related Questions