ぼざクリ タグ広場 https://hub.nizika.monster
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.
 
 
 
 
 
 

53 lines
1.8 KiB

  1. require 'mini_magick'
  2. class Post < ApplicationRecord
  3. belongs_to :parent, class_name: 'Post', optional: true, foreign_key: 'parent_id'
  4. belongs_to :uploaded_user, class_name: 'User', optional: true
  5. has_many :post_tags, dependent: :destroy
  6. has_many :tags, through: :post_tags
  7. has_many :user_post_views, dependent: :destroy
  8. has_many :post_similarities_as_post,
  9. class_name: 'PostSimilarity',
  10. foreign_key: :post_id
  11. has_many :post_similarities_as_target_post,
  12. class_name: 'PostSimilarity',
  13. foreign_key: :target_post_id
  14. has_one_attached :thumbnail
  15. def as_json options = { }
  16. super(options).merge({ thumbnail: thumbnail.attached? ?
  17. Rails.application.routes.url_helpers.rails_blob_url(
  18. thumbnail, only_path: false) :
  19. nil })
  20. rescue
  21. super(options).merge(thumbnail: nil)
  22. end
  23. def related(limit: nil)
  24. ids_with_cos =
  25. post_similarities_as_post.select(:target_post_id, :cos)
  26. .map { |ps| [ps.target_post_id, ps.cos] } +
  27. post_similarities_as_target_post.select(:post_id, :cos)
  28. .map { |ps| [ps.post_id, ps.cos] }
  29. sorted = ids_with_cos.sort_by { |_, cos| -cos }
  30. ids = sorted.map(&:first)
  31. ids = ids.first(limit) if limit
  32. Post.where(id: ids).index_by(&:id).values_at(*ids)
  33. end
  34. def resized_thumbnail!
  35. return unless thumbnail.attached?
  36. image = MiniMagick::Image.read(thumbnail.download)
  37. image.resize '180x180'
  38. thumbnail.purge
  39. thumbnail.attach(io: File.open(image.path),
  40. filename: 'resized_thumbnail.jpg',
  41. content_type: 'image/jpeg')
  42. end
  43. end