#59 関聯投稿一覧の追加

This commit is contained in:
2025-08-01 01:06:09 +09:00
parent 0f902f0d27
commit efb6b16412
4 changed files with 31 additions and 5 deletions
+21
View File
@@ -7,6 +7,12 @@ class Post < ApplicationRecord
has_many :post_tags, dependent: :destroy
has_many :tags, through: :post_tags
has_many :user_post_views, dependent: :destroy
has_many :post_similarities_as_post,
class_name: 'PostSimilarity',
foreign_key: :post_id
has_many :post_similarities_as_target_post,
class_name: 'PostSimilarity',
foreign_key: :target_post_id
has_one_attached :thumbnail
def as_json options = { }
@@ -18,6 +24,21 @@ class Post < ApplicationRecord
super(options).merge(thumbnail: nil)
end
def related(limit: nil)
ids_with_cos =
post_similarities_as_post.select(:target_post_id, :cos)
.map { |ps| [ps.target_post_id, ps.cos] } +
post_similarities_as_target_post.select(:post_id, :cos)
.map { |ps| [ps.post_id, ps.cos] }
sorted = ids_with_cos.sort_by { |_, cos| -cos }
ids = sorted.map(&:first)
ids = ids.first(limit) if limit
Post.where(id: ids)
end
def resized_thumbnail!
return unless thumbnail.attached?