views:

37

answers:

2

Hey guys, I'd like to track how many times a user logs in to my site which is a Rails app. Is there any other call like "created_on or updated_on" that can make a little counter in my model that tracks that kind of info? I'm using restful-authentication currently.

+2  A: 

You could create a column in the user table called login_count or something and then in the SessionsController.create method

if user
    user.login_count += 1
    user.save(false)     #update without validations.

    # .... other RestfulAuthentication generated code ....
Lukas
+2  A: 

I would add login_count field to your User/Account model. Then change this method in User/Account model:

def self.authenticate(login, password)
  return nil if login.blank? || password.blank?
  u = find_by_login(login) # need to get the salt
  u && u.authenticated?(password) ? u.increase_login_count : nil
end

and add this method to model:

def increase_login_count
  self.login_count += 1
  self.save
  self
end
klew
Is there any reason why this would be preferable to the answer by Lukas?
ChrisWesAllen
I find it better because everything stays in model and not in controller. It will help your database to be consistent.
klew