From a7ac41482abdc676dce2d9b6236c428c3bbf950c Mon Sep 17 00:00:00 2001 From: Adrien POLY Date: Thu, 14 Sep 2023 08:02:06 +0200 Subject: [PATCH] remove n+1 talks controller with meilisearch --- app/controllers/talks_controller.rb | 2 +- app/models/talk.rb | 11 +++++++++-- app/views/talks/_card.html.erb | 2 +- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/app/controllers/talks_controller.rb b/app/controllers/talks_controller.rb index 0973b059..b0c483cf 100644 --- a/app/controllers/talks_controller.rb +++ b/app/controllers/talks_controller.rb @@ -9,7 +9,7 @@ def index @from_talk_id = session[:from_talk_id] session[:from_talk_id] = nil if params[:q].present? - talks = Talk.pagy_search(params[:q]) + talks = Talk.includes(:speakers, :event).pagy_search(params[:q]) @pagy, @talks = pagy_meilisearch(talks, items: 9, page: session[:talks_page]&.to_i || 1) else @pagy, @talks = pagy(Talk.all.order(date: :desc).includes(:speakers, :event), items: 9, page: session[:talks_page]&.to_i || 1) diff --git a/app/models/talk.rb b/app/models/talk.rb index 73896733..31fe060e 100644 --- a/app/models/talk.rb +++ b/app/models/talk.rb @@ -28,6 +28,7 @@ class Talk < ApplicationRecord include Suggestable slug_from :title include MeiliSearch::Rails + ActiveRecord_Relation.include Pagy::Meilisearch extend Pagy::Meilisearch # associations @@ -51,10 +52,13 @@ class Talk < ApplicationRecord attribute :thumbnail_sm attribute :thumbnail_md attribute :thumbnail_lg - attribute :speakers do + attribute :speaker_names do speakers.pluck(:name) end - searchable_attributes [:title, :description] + attribute :event_name do + event_name + end + searchable_attributes [:title, :description, :speaker_names, :event_name] sortable_attributes [:title] attributes_to_highlight ["*"] @@ -62,6 +66,9 @@ class Talk < ApplicationRecord meilisearch enqueue: true + # ensure that during the reindex process the associated records are eager loaded + scope :meilisearch_import, -> { includes(:speakers, :event) } + def to_meta_tags { title: title, diff --git a/app/views/talks/_card.html.erb b/app/views/talks/_card.html.erb index e907faaf..495d55b6 100644 --- a/app/views/talks/_card.html.erb +++ b/app/views/talks/_card.html.erb @@ -26,7 +26,7 @@ <% if talk.event %>
<%= heroicon :map_pin, size: :sm, class: "shrink-0 grow-0" %> - <%= content_tag :div, talk.event.name %> + <%= content_tag :div, talk.event_name %>
<%#= link_to talk.event.name, talk.event %> <% end %>