In my User model, I have a 'sign_in_count' column which I initially set to 1 when the user is created:
class User < ActiveRecord::Base
before_save { self.sign_in_count = 1 }
end
This works as when I go to the rails console, I can get back 1:
u = User.last
u.sign_in_count
=> 1
Then I created a method in my SessionsHelper:
def sign_in_count(user)
user.sign_in_count += 1
end
Then I call it my SessionsController like so:
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
sign_in_count(user)
.
.
.
end
But the sign_in_count never seems to increment. I log in perfectly fine. I get no errors or anything. I inspect the console and the sign_in_count is always 1. Any idea as to what i'm doing wrong here?
Use increment
method (detail) instead of, like this:
def sign_in_count(user)
user.increment!(:sign_in_count)
end
And, please change before_save
callback to before_create
callback. We just initialize sign_in_count
only one time when new user is created.
In case of you want to decrease sign_in_count
, please use decrement
.
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