Home > Software design >  Most performant way to load associations in rails
Most performant way to load associations in rails

Time:04-10

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.

CodePudding user response:

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)

CodePudding user response:

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
  • Related