From 1de91658c7d6b3776c9cbe5d03bfe5aab3d2c594 Mon Sep 17 00:00:00 2001 From: rgarcia Date: Wed, 18 Nov 2015 10:19:02 +0100 Subject: [PATCH] extracts cached tsvector to concern --- app/models/concerns/search_cache.rb | 25 +++++++++++++++++++++++++ app/models/proposal.rb | 17 ++--------------- 2 files changed, 27 insertions(+), 15 deletions(-) create mode 100644 app/models/concerns/search_cache.rb diff --git a/app/models/concerns/search_cache.rb b/app/models/concerns/search_cache.rb new file mode 100644 index 000000000..04e3869f8 --- /dev/null +++ b/app/models/concerns/search_cache.rb @@ -0,0 +1,25 @@ +module SearchCache + extend ActiveSupport::Concern + + included do + after_save :calculate_tsvector + end + + def calculate_tsvector + ActiveRecord::Base.connection.execute(" + UPDATE proposals SET tsv = (to_tsvector('spanish', #{fields_to_sql})) WHERE id = #{self.id}") + end + + def fields_to_sql + fields.collect { |field| "coalesce(#{field},'')" }.join(" || ' ' || ") + end + + def fields + searchable_fields << tags_to_sql + end + + def tags_to_sql + "\'#{tag_list.join(' ')}\'" + end + +end \ No newline at end of file diff --git a/app/models/proposal.rb b/app/models/proposal.rb index 84718a5d2..21f379309 100644 --- a/app/models/proposal.rb +++ b/app/models/proposal.rb @@ -5,6 +5,7 @@ class Proposal < ActiveRecord::Base include Measurable include Sanitizable include PgSearch + include SearchCache apply_simple_captcha acts_as_votable @@ -28,7 +29,6 @@ class Proposal < ActiveRecord::Base validates :terms_of_service, acceptance: { allow_nil: false }, on: :create before_validation :set_responsible_name - before_validation :calculate_tsvector before_save :calculate_hot_score, :calculate_confidence_score @@ -59,20 +59,7 @@ class Proposal < ActiveRecord::Base } def searchable_fields - %w(title question summary description) << tags_to_sql - end - - def tags_to_sql - "\'#{tag_list.join(' ')}\'" - end - - def searchable_content - searchable_fields.collect { |field| "coalesce(#{field},'')" }.join(" || ' ' || ") - end - - def calculate_tsvector - ActiveRecord::Base.connection.execute(" - UPDATE proposals SET tsv = (to_tsvector('spanish', #{searchable_content})) WHERE id = #{self.id}") + %w(title question summary description) end def description