I have nested models like (using PostgresSQL)
class User
has_many :details
end
class Page
has_many :details
belongs_to :user
end
class Detail
belongs_to :page
#It has a column named "count"
end
What I need is say User with id=1, it has many pages with ids= 1,2,3. these pages with ids(1,2,3) has many details. What I need is to get latest detail of each of these pages and get sum of field named "counts" from these latest details
What I 'm doing now is
page_ids = current_user.pages.pluck(:id)
last_followers = Detail.select("DISTINCT ON(page_id) *").where(page_id: page_ids).order("page_id, created_at DESC")
last_followers.each { |detail| last_sum += detail.counts }
But it doesn't look ok to find page_ids, than details and than looping through all of them.
Is there a direct way like single query, thanks
Aucun commentaire:
Enregistrer un commentaire