Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sign in count per day in Devise

Is there any way to find out how many unique logins per day a user has?

We can track a user to find out how many sign_in's or when the user signed in with:

User.last.sign_in_count

or

User.last.last_sign_in_at

But not how many time he logged in each day.

like image 544
Eduardo Maia Avatar asked Oct 16 '25 15:10

Eduardo Maia


1 Answers

Here is what I did in my rails app:

I created a new model to track each visit

rails g model Visit user_id:integer user_ip:inet user_email:string

Then

rake db:migrate

Next I created a controller to track sessions with

app/controllers/track_sessions_controller.rb

info about devise session controller

Then I added code to run after each successful login

class TrackSessionsController < Devise::SessionsController
  after_filter :after_login, :only => :create

  def after_login
    Visit.create!(user_id: current_user.id, user_ip: current_user.current_sign_in_ip, user_email: current_user.email)
  end
end

Then update this section of your routes.rb

devise_for :users

to

devise_for :users, :controllers => { :sessions => "track_sessions" }

If you wanted to see how many unique logins per day a user has, you can now do something like this:

User.all.each do |user|
  logins_per_day(user.id) 
end

def logins_per_day(user_id)
  dates_visited = Visit.where(user_id: user_id).select('distinct created_at').all.collect{|x| x[:created_at].to_date}
  puts "************* USER ID #{user_id} *************"
  dates_visited.group_by {|date| date}.map {|date_visited, times_visited| puts "Date Visited: #{date_visited} Times Visited: #{times_visited.count}"}
end
like image 68
jtlindsey Avatar answered Oct 18 '25 03:10

jtlindsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!