ruby on rails - Can i write this Query in ActiveRecord -
for data analysis need both results 1 set.
a.follower_trackings.pluck(:date, :new_followers, :deleted_followers) a.data_trackings.pluck(:date, :followed_by_count)
instead of ugly-merging array (they can have different starting dates , obv. need values date exists in both arrays) thought mysql
select followers.new_followers, followers.deleted_followers, trackings.date, trackings.followed_by_count instagram_user_follower_trackings followers, instagram_data_trackings trackings followers.date = trackings.date , followers.user_id=5 , trackings.user_id=5 order trackings.date desc
this working fine, wonder if can write same activerecord?
you can following should render same query raw sql, it's quite ugly...:
a.follower_trackings. merge(a.data_trackings). from("instagram_user_follower_trackings, instagram_data_trackings"). where("instagram_user_follower_trackings.date = instagram_data_trackings.date"). order(:date => :desc). pluck("instagram_data_trackings.date", :new_followers, :deleted_followers, :followed_by_count)
there few tricks turned out useful while playing scopes: merge
trick adds data_trackings.user_id = a.id
condition not join in data_trackings
, that's why from
clause has added, performs inner join. rest pretty straightforward , leverages fact order
, pluck
clauses not need table name specified if columns either unique among tables, or specified in select (pluck
).
well, when looking again, rather define scope retrieving data given user (a
record) use raw sql have in question. might define helper instance method call scope self
, like:
def model scope :tracking_info, ->(user) { ... } def tracking_info model.tracking_info(self) end end
then 1 can use simply:
a = model.find(1) a.tracking_info # => [[...], [...]]
Comments
Post a Comment