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

131
Visualizações
Most performant way to load associations in rails

I'm trying to load a nested association, a User can belong to many Groups and I want to load all Posts from Groups where the user is a member, but only the posts no the groups as well.

Something like current_user.groups.eager_load(:posts), but without nesting posts under groups.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

I'm assuming Post belongs to Group here.

Start with the model that you need to load and build the query from there. If user belongs to 2 groups here, this will load all the posts from those 2 groups.

Post.where(group: current_user.groups)
over 4 years ago · Santiago Trujillo Relatório

0

You can set up a shortcut from User to Post with has_many :through

class User < ApplicationRecord
  has_and_belongs_to_many :groups
  has_many :posts, through: :groups

  # if User already has a `has_many :posts`, you'll need 
  # to give the through-association a unique name like this:
  # has_many :group_posts, through: :groups, source: :posts
end

class Group < ApplicationRecord
  has_and_belongs_to_many :users
  has_many :posts
end

class Post < ApplicationRecord
  belongs_to :group

  # optionally, you can define the inverse here as well
  # has_many :users, through: :group
end
...

# eager_load on a query: User.includes(:posts) or User.eager_load(:posts)
# get from current user: current_user.posts
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