Skip to content

Instantly share code, notes, and snippets.

@rubyconvict
Forked from sqrtsanta/activity_finder.rb
Last active August 23, 2017 07:24
Show Gist options
  • Save rubyconvict/655ad94244e7d086b030bc0e0bd08176 to your computer and use it in GitHub Desktop.
Save rubyconvict/655ad94244e7d086b030bc0e0bd08176 to your computer and use it in GitHub Desktop.
Preload associations of polymorphic objects
# 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