Skip to content

Instantly share code, notes, and snippets.

@dimroc
Last active December 28, 2020 21:36
Show Gist options
  • Save dimroc/ccc6c80c747ee8f957f3 to your computer and use it in GitHub Desktop.
Save dimroc/ccc6c80c747ee8f957f3 to your computer and use it in GitHub Desktop.
How to eager load AR associations when using Elasticsearch-rails and Kaminari
class EagerPagination < SimpleDelegator
attr_reader :records, :scope
def initialize(records, scope)
super(records)
@records = records
@scope = scope
end
def each
records.public_send(scope).each do |r|
yield r
end
end
end
class GiftsController < ApplicationController
def index
records = Gift.search('flower').page(params[:page]).records
@gifts = EagerPagination.new(records, :eager)
end
# Breaks when using Kaminari pagination because the `page`
# decorator is lost on `.includes(:user)`
def failing_index
@gifts = Gift.search('flower')
.page(params[:page]).records.includes(:user)
end
end
class Gift
include Elasticsearch::Model
belongs_to :user
scope :eager, -> { includes(:user) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment