Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails Increment Counter in Model

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.

like image 299
febs Avatar asked Feb 16 '11 16:02

febs


1 Answers

If User has many Counts and Count belongs to User (like it seems to be), then you might want to use a counter cache. It does exactly what you want to do, and it is built-in into ActiveRecord.

like image 159
Simone Carletti Avatar answered Sep 28 '22 19:09

Simone Carletti