Last active
December 28, 2020 21:36
-
-
Save dimroc/ccc6c80c747ee8f957f3 to your computer and use it in GitHub Desktop.
How to eager load AR associations when using Elasticsearch-rails and Kaminari
This file contains 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 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 |
This file contains 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 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 |
This file contains 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 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