ruby - how to count all page impressions from two different models into one number? (rails 3) -


i'm using impressionist gem , works well.

i using in user/show.html.erb view count impressions of person's profile (user.rb impressionable)

<%= @user.impressionist_count %> 

i decided break out each micropost user , decided count (micropost.rb impressionable)

in micropost/show.html.erb - using code count how many times particular post viewed

<%= @micropost.impressionist_count %> 

i trying sum of @micropost.impressionist_count fall under same user , add user/show.html.erb. how can that?

so in mathematical terms, i'm trying do

total = user.impressionist_count + sum(micropost.impressionist_count)s

you haven't specified database using gem. it's compatible rdbms database, mongodb. summing may perform differently depending on choice.

in rdbms-backed system, can eager load of related microposts given user through use of join (:joins in ar parlance). having grabbed of related microposts, can do:

@user.impressionist_count + @user.microposts.sum(&:impressionist_count) 

rails gives enumerable#sum (http://api.rubyonrails.org/classes/enumerable.html#method-i-sum) can use that.

the difference can see, mongo concerned, amount of requests you're going make database unless you've embedded microposts each user document.

hope helps.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -