7

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
pzupan
  • 169
  • 1
  • 7

3 Answers3

5

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!

5

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.

chickensmitten
  • 477
  • 6
  • 16
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.

Patrick
  • 165
  • 2
  • 13
  • Thank you, this worked very well for me. I wrote up a detailed explanation of it here in hopes it will help others: https://www.donnfelker.com/pgsearch-multisearch-with-action-text-rich-text/ – Donn Felker Mar 27 '22 at 11:31