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

66 lines
1.6 KiB

  1. class PostsController < ApplicationController
  2. before_action :set_post, only: %i[ show update destroy ]
  3. # GET /posts
  4. def index
  5. if params[:tags].present?
  6. tag_names = params[:tags].split(',')
  7. match_type = params[:match]
  8. if match_type == 'any'
  9. @posts = Post.joins(:tags).where(tags: { name: tag_names }).distinct
  10. else
  11. @posts = Post.joins(:tags)
  12. tag_names.each do |tag|
  13. @posts = @posts.where(id: Post.joins(:tags).where(tags: { name: tag }))
  14. end
  15. @posts = @posts.distinct
  16. end
  17. else
  18. @posts = Post.all
  19. end
  20. render json: @posts.as_json(include: { tags: { only: [:id, :name, :category] } })
  21. end
  22. # GET /posts/1
  23. def show
  24. @post = Post.includes(:tags).find(params[:id])
  25. render json: @post.as_json(include: { tags: { only: [:id, :name, :category] } })
  26. end
  27. # POST /posts
  28. def create
  29. @post = Post.new(post_params)
  30. if @post.save
  31. render json: @post, status: :created, location: @post
  32. else
  33. render json: @post.errors, status: :unprocessable_entity
  34. end
  35. end
  36. # PATCH/PUT /posts/1
  37. def update
  38. if @post.update(post_params)
  39. render json: @post
  40. else
  41. render json: @post.errors, status: :unprocessable_entity
  42. end
  43. end
  44. # DELETE /posts/1
  45. def destroy
  46. @post.destroy!
  47. end
  48. private
  49. # Use callbacks to share common setup or constraints between actions.
  50. def set_post
  51. @post = Post.find(params.expect(:id))
  52. end
  53. # Only allow a list of trusted parameters through.
  54. def post_params
  55. params.expect(post: [ :title, :body ])
  56. end
  57. end