如何在Rails的动作文本中包含Pgsearch

时间:2019-02-03 19:01:39

标签: ruby-on-rails pg-search

我正在将pgsearch添加到Rails 6动作文本中,并且不确定将pgsearch包含在RichText模型中的最佳技术。我似乎无法不破坏模型就修补猴子模型。我确实通过完全替换模型来使其正常工作,但是显然不希望这样。任何想法如何使这项工作?这是我当前的模型:

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

3 个答案:

答案 0 :(得分:0)

我已经使用associated_against解决了ActionText + PgSearch-puzzle,这不完全是您所要的,但也许可以解决您的问题。

class Article < ApplicationRecord
  include PgSearch

  has_rich_text :content

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

祝一切顺利!

答案 1 :(得分:0)

@ dirk-sierd-de-vries的回答对我来说并不立即明显。因此,我将添加一个示例供我学习和将来参考。

class Book < ApplicationRecord
  include PgSearch

  has_rich_text :chapter

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

在命令行中搜索book.chapter时,将获得以下信息:

#<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">

因此,associated_against必须为body

答案 2 :(得分:0)

如果你想让 ActionText::RichText 字段可以多搜索,你可以做的(从这个 tutorial 借用)是在 config/initializers/action_text_rich_text.rb 中添加一个初始化器:

ActiveSupport.on_load :action_text_rich_text do
  include PgSearch::Model

  multisearchable against: :body
end

这样你就可以“安全地”猴子补丁。

请注意,如果 PgSearch.multisearch("YOUR QUERY").first.searchable.is_a?(ActionText::RichText),则必须对其调用 .record 才能访问富文本附加到的实际 ActiveRecord 对象。