Reputation: 43
I'm using the impressionist gem and it works well.
I am using this in my user/show.html.erb view to count all impressions of a person's profile (user.rb is impressionable)
<%= @user.impressionist_count %>
I decided to break out each micropost by a user and decided to count that as well (micropost.rb is impressionable)
In micropost/show.html.erb
- I am using this code to count how many times a particular post was viewed
<%= @micropost.impressionist_count %>
I am trying to sum up ALL of the @micropost.impressionist_count that fall under the same user and add it to the user/show.html.erb. How can I do that?
So In mathematical terms, this is what I'm trying to do
total = user.impressionist_count + sum(micropost.impressionist_count)s
Upvotes: 1
Views: 399
Reputation: 8202
You haven't specified what database you are using with this gem. It's compatible with an RDBMS database, as well as with MongoDB. The summing may perform differently depending on that choice.
In an RDBMS-backed system, you can simply eager load all of the related microposts for a given user through the use of a JOIN (:joins in AR parlance). Having grabbed all of related microposts, you can simply do:
@user.impressionist_count + @user.microposts.sum(&:impressionist_count)
Rails gives you the Enumerable#sum (http://api.rubyonrails.org/classes/Enumerable.html#method-i-sum) which you can use for that.
The only difference that I can see, where Mongo is concerned, is the amount of requests you're going to make to the database unless you've embedded the microposts into each User document.
Hope this helps.
Upvotes: 1