开发者

Ruby on Rails Increment Counter in Model

开发者 https://www.devze.com 2023-02-10 17:03 出处:网络
I\'m attempting to increment a counter in my User table from another model. class Coun开发者_JS百科t < ActiveRecord::Base

I'm attempting to increment a counter in my User table from another model.

class Coun开发者_JS百科t < 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.


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.


I think a better place for this would be using an observer that listens for the on_create for User objects, and then runs this logic.

Something like:

class UserObserver < ActiveRecord::Observer
  def after_create(user)
    Counter.find_by_name("user_count").increment
  end
end


If you would like more extensible counter caches, check out counter_culture. It supports basic counter cache functionality, but also allows you to create counters of records that meet various conditions. For example, you could easily create an inactive user count with code like this:

class Product < ActiveRecord::Base
  belongs_to :category
  counter_culture :category, :column_name => \
    Proc.new {|model| model.inactive? ? 'inactive_count' : nil }
end
0

精彩评论

暂无评论...
验证码 换一张
取 消