I have a User with has_many articles. In order to display(count) number of articles created by user I will call @user.articles.count.
It will internaly run sql query on articles table. In order to eliminate the external query for displaying the count(i.e number of articles) active record associations provides usefull option for that.
Say a User has_many articles. In the articles model, add a line blongs_to :user, counter_cache: true. Add an integer column to the user table named articles_count. Whenever you create a article, the counter will be updated. See http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to (:counter_cache section).
:counter_cache
Caches the number of belonging objects on the associate class through the use of increment_counter and decrement_counter. The counter cache is incremented when an object of this class is created and decremented when it’s destroyed. This requires that a column named #{table_name}_count (such as comments_count for a belonging Comment class) is used on the associate class (such as a Post class). You can also specify a custom counter cache column by providing a column name instead of a true/false value to this option (e.g., :counter_cache => :my_custom_counter.) Note: Specifying a counter cache will add it to that model’s list of readonly attributes using attr_readonly.
Thank you,
Uma Mahesh
It will internaly run sql query on articles table. In order to eliminate the external query for displaying the count(i.e number of articles) active record associations provides usefull option for that.
Say a User has_many articles. In the articles model, add a line blongs_to :user, counter_cache: true. Add an integer column to the user table named articles_count. Whenever you create a article, the counter will be updated. See http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to (:counter_cache section).
:counter_cache
Caches the number of belonging objects on the associate class through the use of increment_counter and decrement_counter. The counter cache is incremented when an object of this class is created and decremented when it’s destroyed. This requires that a column named #{table_name}_count (such as comments_count for a belonging Comment class) is used on the associate class (such as a Post class). You can also specify a custom counter cache column by providing a column name instead of a true/false value to this option (e.g., :counter_cache => :my_custom_counter.) Note: Specifying a counter cache will add it to that model’s list of readonly attributes using attr_readonly.
Thank you,
Uma Mahesh
No comments:
Post a Comment