Created
April 22, 2015 11:33
-
-
Save sqrtsanta/4ae4341f3fd2d2bf2d39 to your computer and use it in GitHub Desktop.
Preload associations of polymorphic objects
This file contains hidden or 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
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