Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

261
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda