Marcin Adamczyk
Marcin Adamczyk

Reputation: 509

Preload assocation with scope and argument in Rails

Assuming we have something like this:

class Group < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  scope :have_more_than_X_posts, -> (x) { where('posts_count > ?', x) }
end

I want to be able to call something like this: Group.includes(users: {have_more_than_X_posts: 10})

Ideas?

Upvotes: 1

Views: 541

Answers (1)

We can achieve that with a private Rails API, so use it with caution, as it might change significantly. For Rails 7+, we can do this:

@group = Group.all
ActiveRecord::Associations::Preloader.new(records: @group,
                                          associations: :users,
                                          scope: User.have_more_than_X_posts(10)).call

puts @group.users

Upvotes: 0

Related Questions