Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

260
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda