ruby on rails - Summing different columns and returning array for chart -


i have article model (which belongs user) , holds number of facebook_shares, linkedin_shares , twitter_shares. i'd sum number of facebook/linkedin/twitter shares each user's articles , return them array can put chart.

this how i'm doing it, returning results in =content_tag per railcast:

 = content_tag :div, "", id: "shares-chart", data: {shares:     [      {y: 'tweets', a: @user.articles.sum(:twitter_shares)},      {y: 'facebook', a: @user.articles.sum(:facebook_shares)},      {y: 'linkedin', a: @user.articles.sum(:linkedin_shares)}    ]   } 

but seems ugly way. there nicer way using .map? it's function can't figure out how apply columns, rather records.

maybe want this:

in user model:

def construct_data   [{"tweets" => :twitter_shares}, {"facebook" => :facebook_shares}, {"linkedin" => :linkedin_shares}].map |h|      {y: h.keys.first, a: @user.articles.sum(h.values.first)}   end  end 

in controller action:

@chart_data = @user.construct_data 

in view:

 = content_tag :div, "", id: "shares-chart", data: {shares: @chart_data} 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

javascript - Clean way to programmatically use CSS transitions from JS? -

android - send complex objects as post php java -