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

132
Views
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 answers
Answer question

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 Report

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 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!