You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
800 B

8 years ago
8 years ago
  1. # frozen_string_literal: true
  2. class Tag < ApplicationRecord
  3. has_and_belongs_to_many :statuses
  4. HASHTAG_RE = /(?:^|[^\/\)\w])#([[:word:]_]*[[:alpha:]_][[:word:]_]*)/i
  5. validates :name, presence: true, uniqueness: true
  6. def to_param
  7. name
  8. end
  9. class << self
  10. def search_for(terms, limit = 5)
  11. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  12. textsearch = 'to_tsvector(\'simple\', tags.name)'
  13. query = 'to_tsquery(\'simple\', \'\'\' \' || ' + terms + ' || \' \'\'\' || \':*\')'
  14. sql = <<SQL
  15. SELECT
  16. tags.*,
  17. ts_rank_cd(#{textsearch}, #{query}) AS rank
  18. FROM tags
  19. WHERE #{query} @@ #{textsearch}
  20. ORDER BY rank DESC
  21. LIMIT ?
  22. SQL
  23. Tag.find_by_sql([sql, limit])
  24. end
  25. end
  26. end