ぼざクリ タグ広場 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.
 
 
 
 
 
 

73 lines
2.4 KiB

  1. class Post < ApplicationRecord
  2. require 'mini_magick'
  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, inverse_of: :post
  6. has_many :active_post_tags, -> { kept }, class_name: 'PostTag', inverse_of: :post
  7. has_many :post_tags_with_discarded, -> { with_discarded }, class_name: 'PostTag'
  8. has_many :tags, through: :active_post_tags
  9. has_many :user_post_views, dependent: :destroy
  10. has_many :post_similarities_as_post,
  11. class_name: 'PostSimilarity',
  12. foreign_key: :post_id
  13. has_many :post_similarities_as_target_post,
  14. class_name: 'PostSimilarity',
  15. foreign_key: :target_post_id
  16. has_one_attached :thumbnail
  17. validate :validate_original_created_range
  18. def as_json options = { }
  19. super(options).merge({ thumbnail: thumbnail.attached? ?
  20. Rails.application.routes.url_helpers.rails_blob_url(
  21. thumbnail, only_path: false) :
  22. nil })
  23. rescue
  24. super(options).merge(thumbnail: nil)
  25. end
  26. def related(limit: nil)
  27. ids_with_cos =
  28. post_similarities_as_post.select(:target_post_id, :cos)
  29. .map { |ps| [ps.target_post_id, ps.cos] } +
  30. post_similarities_as_target_post.select(:post_id, :cos)
  31. .map { |ps| [ps.post_id, ps.cos] }
  32. sorted = ids_with_cos.sort_by { |_, cos| -cos }
  33. ids = sorted.map(&:first)
  34. ids = ids.first(limit) if limit
  35. Post.where(id: ids).index_by(&:id).values_at(*ids)
  36. end
  37. def resized_thumbnail!
  38. return unless thumbnail.attached?
  39. image = MiniMagick::Image.read(thumbnail.download)
  40. image.resize '180x180'
  41. thumbnail.purge
  42. thumbnail.attach(io: File.open(image.path),
  43. filename: 'resized_thumbnail.jpg',
  44. content_type: 'image/jpeg')
  45. end
  46. private
  47. def validate_original_created_range
  48. f = original_created_from
  49. b = original_created_before
  50. return if f.blank? || b.blank?
  51. f = Time.zone.parse(f) if String === f
  52. b = Time.zone.parse(b) if String === b
  53. return if !(f) || !(b)
  54. if f >= b
  55. errors.add :original_created_before, 'オリジナルの作成日時の順番がをかしぃです.'
  56. end
  57. end
  58. end