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.

42 lines
1.0 KiB

7 years ago
7 years ago
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: tags
  5. #
  6. # id :integer not null, primary key
  7. # name :string default(""), not null
  8. # created_at :datetime not null
  9. # updated_at :datetime not null
  10. #
  11. class Tag < ApplicationRecord
  12. has_and_belongs_to_many :statuses
  13. HASHTAG_RE = /(?:^|[^\/\)\w])#([[:word:]_]*[[:alpha:]_][[:word:]_]*)/i
  14. validates :name, presence: true, uniqueness: true
  15. def to_param
  16. name
  17. end
  18. class << self
  19. def search_for(terms, limit = 5)
  20. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  21. textsearch = 'to_tsvector(\'simple\', tags.name)'
  22. query = 'to_tsquery(\'simple\', \'\'\' \' || ' + terms + ' || \' \'\'\' || \':*\')'
  23. sql = <<-SQL.squish
  24. SELECT
  25. tags.*,
  26. ts_rank_cd(#{textsearch}, #{query}) AS rank
  27. FROM tags
  28. WHERE #{query} @@ #{textsearch}
  29. ORDER BY rank DESC
  30. LIMIT ?
  31. SQL
  32. Tag.find_by_sql([sql, limit])
  33. end
  34. end
  35. end