How to find the count of the associated models with less number of queries being executed?
64 views
Skip to first unread message
Logesh m
unread,
Nov 6, 2014, 1:40:42 AM11/6/14
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to rubyonra...@googlegroups.com
I have a rails app where I need to take count of the associated model like post.comments.count and this loads up number of queries and I was searching for option to reduce this and found counter cache which saves the count in the table but is there any other option to find the count without saving in the table?
Thanks in advance.
Alvaro Naveda
unread,
Nov 6, 2014, 5:17:39 AM11/6/14
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to rubyonra...@googlegroups.com
The best solution i know to solve this issue with less number of queries is the counter_cache ;)
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to rubyonra...@googlegroups.com
This is really simple, but surprisingly effective: If you already have post.comments, then call post.comments.length on it instead of post.comments.count on it and it won't make another SELECT COUNT(*) query.
Otherwise, counter cache.
Logesh m
unread,
Nov 7, 2014, 1:20:32 AM11/7/14
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to rubyonra...@googlegroups.com
In case of counter cache, for example, how can I specify a condition to select the count of comments that I have marked as valid something like shown below
belongs_to :post, :counter_cache => true, :conditions => ["valid IS NOT NULL"]
Alvaro Naveda
unread,
Nov 7, 2014, 4:10:37 AM11/7/14
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to rubyonra...@googlegroups.com
You can supply the counter column name (apart from true) to the counter_cache option.