Skip to content

Instantly share code, notes, and snippets.

@sqrtsanta
Created April 22, 2015 11:33
Show Gist options
  • Save sqrtsanta/4ae4341f3fd2d2bf2d39 to your computer and use it in GitHub Desktop.
Save sqrtsanta/4ae4341f3fd2d2bf2d39 to your computer and use it in GitHub Desktop.
Preload associations of polymorphic objects
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