ruby - Rails loop through ActiveRecord::Associations:CollectionProxy -
i've got activerecord::associations:collectionproxy
of format
#<dailyviewmetric article_id: xxxxxx, date: xxxxxxx, views: xxxxxx, visitors xxxxx,.....>
in variable called metrics
.
the article_id foreign key , repeated in table (as 1 article can have metrics on consecutive days (i.e. 15 views today , 20 day after).
i need way loop through , apply different operations of these metrics smallesest date each article, total number of views (= sum(views)). tried metrics.map |a|
, metrics.collect
ruby errors undefined method 'views'
example let's go following simplified dataset
article_id date views 1 2014-01-01 10 2 2014-01-01 15 1 2014-01-02 20 2 2014-01-02 12 3 2014-01-02 6
should result in following new array afterwards:
article_id date views 1 2014-01-01 30 2 2014-01-01 27 3 2014-01-02 6
as can see views variable holds sum of views respective article, date variable minimum of dates. how do properly? tried metrics.to_a
still error.
edit
i tried dailyviewmetric.find_by_sql("select article_id, sum(views) daily_view_metrics article_id in(select id articles user_id=xxx) group article_id")
which, if execute query in mysql console, works fine , returns second table above. when run in rails console gives me
[#<dailyviewmetric id: nil, article_id: 1089536>, #<dailyviewmetric id: nil, article_id: 1128849>, #<dailyviewmetric id: nil, article_id: 1141623>,
you can in sql/activerecord. query want run is
select article_id, min(date), sum(views) daily_value_metrics -- or whatever table called group article_id
you can run activerecord following:
table = dailyvaluemetric.arel_table results = dailyvaluemetric.select(table[:article_id], table[:date].minimum.as('date'), table[:views].sum.as('views')).group(:article_id).to_a # calling to_a can call first example results.first.date #=> date results.first.views #=> views results.first.article_id #=> id
the records
[#<dailyviewmetric id: nil, article_id: 1089536>, ...]
because sql query not return id column in result set. because of way activerecord::base#inspect
shows columns defined on table, , not returned values outside of table columns. views , date not shown, unless there column same name, if call attributes on model instance, able value
Comments
Post a Comment