Ruby on Rails Increment Counter in Model
Posted
by
febs
on Stack Overflow
See other posts from Stack Overflow
or by febs
Published on 2011-02-16T16:25:24Z
Indexed on
2012/06/18
15:16 UTC
Read the original article
Hit count: 179
I'm attempting to increment a counter in my User table from another model.
class Count < ActiveRecord::Base
belongs_to :user
after_create :update_count
def update_count
user = User.find(self.user_id)
user.increment(:count)
end
end
So when count is created the goal would be to increment a counter column for that user. Currently it refuses to get the user after creation and I get a nil error.
I'm using devise for my Users
Is this the right (best practice) place to do it? I had it working in the controllers, but wanted to clean it up.
I'm very inexperienced with Model callbacks.
© Stack Overflow or respective owner