retrospring/app/models/answer.rb
Georg Gadinger c14bae74d5 attempt to add pg_search
this commit is an attempt at building a search functionality using only
the stuff provided by postgresql

it is, unfortunately, painfully slow:

    PgSearch::Document Load (7869.1ms)  SELECT "pg_search_documents".* FROM "pg_search_documents" INNER JOIN (SELECT "pg_search_documents"."id" AS pg_search_id, (ts_rank((to_tsvector('simple', coalesce("pg_search_documents"."content"::text, ''))), (to_tsquery('simple', ''' ' || 'awoo' || ' ''')), 0)) AS rank FROM "pg_search_documents" WHERE ((to_tsvector('simple', coalesce("pg_search_documents"."content"::text, ''))) @@ (to_tsquery('simple', ''' ' || 'awoo' || ' ''')))) AS pg_search_ce9b9dd18c5c0023f2116f ON "pg_search_documents"."id" = pg_search_ce9b9dd18c5c0023f2116f.pg_search_id ORDER BY pg_search_ce9b9dd18c5c0023f2116f.rank DESC, "pg_search_documents"."id" ASC LIMIT $1  [["LIMIT", 10]]
2023-10-22 18:13:26 +02:00

60 lines
1.9 KiB
Ruby

class Answer < ApplicationRecord
extend Answer::TimelineMethods
include PgSearch::Model
multisearchable against: [:content]
belongs_to :user, counter_cache: :answered_count
belongs_to :question, counter_cache: :answer_count
has_many :comments, dependent: :destroy
has_many :smiles, class_name: "Appendable::Reaction", foreign_key: :parent_id, dependent: :destroy
has_many :subscriptions, dependent: :destroy
has_many :comment_smiles, through: :comments, source: :smiles
# rubocop:disable Rails/UniqueValidationWithoutIndex
# This cop is disabled here because there already are questions with
# multiple answers. Adding an index would break things database-side
validates :question_id, uniqueness: { scope: :user_id }
# rubocop:enable Rails/UniqueValidationWithoutIndex
scope :pinned, -> { where.not(pinned_at: nil) }
SHORT_ANSWER_MAX_LENGTH = 640
after_create do
Inbox.where(user: self.user, question: self.question).destroy_all
user.touch :inbox_updated_at # rubocop:disable Rails/SkipsModelValidations
Notification.notify self.question.user, self unless self.question.user == self.user or self.question.user.nil?
Subscription.subscribe self.user, self
Subscription.subscribe self.question.user, self unless self.question.author_is_anonymous
end
before_destroy do
# mark a report as deleted if it exists
rep = Report.where(target_id: self.id, type: 'Reports::Answer')
rep.each do |r|
unless r.nil?
r.deleted = true
r.save
end
end
self.smiles.each do |smile|
Notification.denotify self.user, smile
end
self.comments.each do |comment|
Subscription.denotify comment, self
end
Notification.denotify question&.user, self
Subscription.destruct self
end
def notification_type(*_args)
Notification::QuestionAnswered
end
def long? = content.length > SHORT_ANSWER_MAX_LENGTH
def pinned? = pinned_at.present?
end