This commit is contained in:
2025-06-29 15:44:40 +09:00
parent 01b45c1a8d
commit 281c85f2f6
4 changed files with 46 additions and 21 deletions
+29 -15
View File
@@ -5,24 +5,18 @@ require 'nokogiri'
class PostsController < ApplicationController
# GET /posts
def index
if params[:tags].present?
tag_names = params[:tags].split(',')
match_type = params[:match]
if match_type == 'any'
posts = Post.joins(:tags).where(tags: { name: tag_names }).distinct
else
posts = Post.joins(:tags)
tag_names.each do |tag|
posts = posts.where(id: Post.joins(:tags).where(tags: { name: tag }))
end
posts = posts.distinct
end
else
posts = Post.all
end
posts = filtered_posts
render json: posts.as_json(include: { tags: { only: [:id, :name, :category] } })
end
def random
post = filtered_posts.order('RAND()').first
viewed = current_user&.viewed?(post)
render json: (post
.as_json(include: { tags: { only: [:id, :name, :category] } })
.merge(viewed: viewed))
end
# GET /posts/1
def show
post = Post.includes(:tags).find(params[:id])
@@ -86,4 +80,24 @@ class PostsController < ApplicationController
# DELETE /posts/1
def destroy
end
private
def filtered_posts
tag_names = params[:tags]&.split(',')
match_type = params[:match]
tag_names.present? ? filter_posts_by_tags(tag_names, match_type) : Post.all
end
def filter_posts_by_tags tag_names, match_type
posts = Post.joins(:tags)
if match_type == 'any'
posts = posts.where(tags: { name: tag_names }).distinct
else
tag_names.each do |tag|
posts = posts.where(id: Post.joins(:tags).where(tags: { name: tag }))
end
end
posts.distinct
end
end