1

I want to track the number of user visits to a site. A visit counter (part of User model) is incremented if prior visit was more then 30 minute ago. I am using Rails and Devise:

class ApplicationController < ActionController::Base
  before_filter :authenticate_user!
  before_filter :update_visits

  def update_visits
    current_user.increment!(:visits) if !current_user.nil? && current_user.updated_at < 30.minutes.ago
  end
end

this would work great, except I have devise :rememberable turned on. So the sequence of SQL calls from :authenticate_user! is this:

SELECT "users".* FROM "users" WHERE "users"."email" = 'person_1@example.com' LIMIT 1

UPDATE "users" SET "remember_created_at" = '2012-11-21 20:13:53.011322', "updated_at" = '2012-11-21 20:13:53.012791' WHERE "users"."id" = 1

So the visits variable is never incremented because updated_at is set to the current time in the rememberable call. How do I put update_visits call after authenticate but before rememberable?

Thank you

Arman
  • 1,208
  • 1
  • 12
  • 17

2 Answers2

0

I think your task is not so simple . In case you have rememberable on , you should track the activities of the users not by signing in . There should be a criteria set what do you call "activity" : is it just returning to the page of the app or some click over a link or a button . In the Railscast about the authentication from scratch there is a logic behind the authentication . Probably there'd be the solution ? Like setting a callback when the session is checked for current_user.

EDIT : Take a look at this discusion. There are a number of ways to track the time of auth request from current user via Warden::Manager .

Community
  • 1
  • 1
R Milushev
  • 4,295
  • 3
  • 27
  • 35
  • yes, that would be a way to an extended solution. For now, all I want is for any user activity on the site to trigger the "updated_at < 30.minutes.ago" check. – Arman Nov 21 '12 at 21:58
  • thank you, i did end up using warden:manager to solve it. i posted my code. – Arman Nov 22 '12 at 23:41
  • That's really great . I've started the same apps feature at the same time . – R Milushev Nov 22 '12 at 23:47
0

I used Warden to solve this.

initializers/devise.rb:

Warden::Manager.after_set_user do |user,auth,opts|
  user.increment(:visits).save! if user.updated_at < 30.minutes.ago
end
Arman
  • 1,208
  • 1
  • 12
  • 17