How to include Pgsearch in Action Text in Rails
Asked Answered
H

3

9

I'm adding pgsearch to Rails 6 Action Text and am not sure the best technique for including pgsearch in the RichText model. I can't seem to monkey patch the model without breaking it. I do have it working by replacing the model entirely, but obviously don't want to leave it that way. Any ideas how to make this work? Here's my current model:

include PgSearch

class ActionText::RichText < ActiveRecord::Base
  self.table_name = "action_text_rich_texts"

  multisearchable :against => :body

  serialize :body, ActionText::Content
  delegate :to_s, :nil?, to: :body

  belongs_to :record, polymorphic: true, touch: true
  has_many_attached :embeds

  before_save do
    self.embeds = body.attachments.map(&:attachable) if body.present?
  end

  def to_plain_text
    body&.to_plain_text.to_s
  end
  delegate :blank?, :empty?, :present?, to: :to_plain_text

end
Haberdasher answered 3/2, 2019 at 19:1 Comment(0)
A
7

I've solved the ActionText+PgSearch-puzzle using associated_against, not entirely what you're asking for, but perhaps it's of use to your problem.

class Article < ApplicationRecord
  include PgSearch

  has_rich_text :content

  pg_search_scope :search, associated_against: {
    rich_text_content: [:body]
  }
end

All the best!

Abrahamsen answered 23/6, 2019 at 18:15 Comment(0)
S
7

The answer from @dirk-sierd-de-vries was not immediately obvious for me. So I am going to add an example for my learning and future reference.

class Book < ApplicationRecord
  include PgSearch

  has_rich_text :chapter

  pg_search_scope :book_search, associated_against: {
    rich_text_chapter: [:body]
  }
end

When you search for book.chapter in the command line, you will get the following:

#<ActionText::RichText id: 1, name: "chapter", body: #<ActionText::Content "<div class=\"trix-conte...">, record_type: "Book", record_id: 1, created_at: "2019-12-31 00:00:00", updated_at: "2019-12-31 00:00:00">

Hence the associated_against would need to be body.

Shcherbakov answered 31/12, 2019 at 1:29 Comment(0)
G
2

If you want to make ActionText::RichText fields multisearchable, what you can do (borrowing from this tutorial) is add an initializer in config/initializers/action_text_rich_text.rb:

ActiveSupport.on_load :action_text_rich_text do
  include PgSearch::Model

  multisearchable against: :body
end

That way you can "safely" monkey patch.

Note that if PgSearch.multisearch("YOUR QUERY").first.searchable.is_a?(ActionText::RichText), you will have to call .record on it to access the actual ActiveRecord object that the rich text is attached to.

Guillermoguilloche answered 9/7, 2021 at 14:48 Comment(1)
Thank you, this worked very well for me. I wrote up a detailed explanation of it here in hopes it will help others: donnfelker.com/pgsearch-multisearch-with-action-text-rich-textAthiste

© 2022 - 2024 — McMap. All rights reserved.