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

166 views Asked by At

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.

2

There are 2 answers

1
achempion On BEST ANSWER

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.

0
Shalev Shalit On

The instance #increment_counter: more oop, and runs #update_all(fast and without validations).