Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

259
Views
Rails, nested has_many association, finding sum of field of last children of each

I have nested models like (using PostgresSQL)

class User
  has_many :pages
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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Not entirely sure of what you ask for but here's a try:

sum = current_user.pages.map { |page| page.details.last.counts }.sum
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!