-
-
Save rubyconvict/655ad94244e7d086b030bc0e0bd08176 to your computer and use it in GitHub Desktop.
Preload associations of polymorphic objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# http://api.rubyonrails.org/classes/ActiveRecord/EagerLoadPolymorphicError.html | |
# https://github.com/chaps-io/public_activity/issues/297 | |
# https://ksylvest.com/posts/2017-08-23/eager-loading-polymorphic-associations-with-ruby-on-rails | |
class ActivityFinder | |
attr_reader :activities, :user | |
def initialize(user) | |
@user = user | |
@activities = Activity.all.where(:user_id => user_ids). | |
with_subject.with_user.desc | |
activities.group_by(&:subject_type).each do |name, group| | |
includes_dependencies(name.downcase.to_sym, group) | |
end | |
end | |
def user_ids | |
user.friend_ids.push(user.id) | |
end | |
def includes_dependencies(name, group) | |
ActiveRecord::Associations::Preloader.new().preload( | |
group, :subject => dependencies.fetch(name, []) | |
) | |
end | |
def dependencies | |
{ | |
:collection => [:tracks], | |
:project => [:something_else] | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment