This commit is contained in:
2025-05-27 01:40:13 +09:00
parent 41668fa894
commit c9c622635c
4 changed files with 156 additions and 25 deletions
+36 -13
View File
@@ -2,14 +2,36 @@ class TagsController < ApplicationController
before_action :set_tags, only: %i[ show update destroy ]
def index
if params[:post].present?
@tags = Tag.joins(:posts).where(posts: { id: params[:post] })
else
@tags = Tag.all
end
@tags =
if params[:post].present?
Tag.joins(:posts).where(posts: { id: params[:post] })
else
Tag.all
end
render json: @tags
end
def autocomplete
q = params[:q].to_s.strip
return render json: [] if q.blank?
tags = (Tag
.left_joins(:posts)
.select('tags.id, tags.name, tags.category, COUNT(posts.id) AS post_count')
.where('(tags.category = ? AND tags.name LIKE ?)
OR tags.name LIKE ?',
'nico', "nico:#{ q }%", "#{ q }%")
.group('tags.id')
.order('post_count DESC, tags.name ASC')
.limit(20))
render json: tags.map do |tag|
{ id: tag.id,
name: tag.name,
category: tag.category,
count: tag.post_count }
end
end
def show
render json: @tag
end
@@ -24,13 +46,14 @@ class TagsController < ApplicationController
end
private
# Use callbacks to share common setup or constraints between actions.
def set_tag
@tag = Tag.find(params.expect(:id))
end
# Only allow a list of trusted parameters through.
def tag_params
params.expect(tag: [ :title, :body ])
end
# Use callbacks to share common setup or constraints between actions.
def set_tag
@tag = Tag.find(params.expect(:id))
end
# Only allow a list of trusted parameters through.
def tag_params
params.expect(tag: [ :title, :body ])
end
end