I am currently struggling with a relation/scope that is dynamic - based on the current time for example.
How do I lazy load/batch the query efficiently? I am already using Dataloaders but they don't seem to work with (dynamic) scope and they are still triggering N+1 for this case.
module Types
class PersonType < BaseObject
field :future_events, [EventType], null: false
def future_events
dataloader.with(Sources::ActiveRecordObject, ::Event.where("start > ?", Time.zone.now), column: :person_id).load(object.id)
# Event.where("start > ?", Time.zone.now).where(person_id: object.id)
end
end
end
module Sources
class ActiveRecordAssociation < GraphQL::Dataloader::Source
def initialize(model_class, column: :id)
@model_class = model_class
@column = column
end
attr_reader :model_class, :column
def fetch(ids, scope = :all)
records = model_class.send(scope).where({ column.to_sym => ids }).index_by { |record| record[column] }
ids.map { |id| records[id] }
end
end
end