Search code examples
ruby-on-railsruby-on-rails-4incrementcounter-cache

Should I use the class or instance method to increment my object?


There are two methods to increment an attribute in Rails:

Instance-level: http://apidock.com/rails/ActiveRecord/Base/increment!
Class-level: http://apidock.com/rails/ActiveRecord/Base/increment_counter/class

I want to update a counter attribute on my Post model that saves the number of comments for a post.

Is any of the two better for my use case?

I will use it with a PostgreSQL database.


Solution

  • For your purpose, I think that you should use an attribute like :counter_cache in AR association. For example:

    class Comment < ActiveRecord::Base
      # cached value will stored into the comments_count column at posts table
      belongs_to :post, counter_cache: true
    end
    
    class Post < ActiveRecord::Base
      has_many :comments
    end
    

    Rails will do a lot of work without your attention.

    For two methods that you mentioned above (increcement_counter and incresement) they are use for different purposes. The increcement_counter is the back magic for counter_cache. The incresement use for just increase some integer value in the table.