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

83 lines
2.0 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. viewed = current_user&.viewed?(@post)
  26. render json: (@post
  27. .as_json(include: { tags: { only: [:id, :name, :category] } })
  28. .merge(viewed: viewed))
  29. end
  30. # POST /posts
  31. def create
  32. @post = Post.new(post_params)
  33. if @post.save
  34. render json: @post, status: :created, location: @post
  35. else
  36. render json: @post.errors, status: :unprocessable_entity
  37. end
  38. end
  39. def viewed
  40. return head :unauthorized unless current_user
  41. current_user.viewed_posts << Post.find(params[:id])
  42. head :no_content
  43. end
  44. def unviewed
  45. return head :unauthorized unless current_user
  46. current_user.viewed_posts.delete(Post.find(params[:id]))
  47. head :no_content
  48. end
  49. # PATCH/PUT /posts/1
  50. def update
  51. if @post.update(post_params)
  52. render json: @post
  53. else
  54. render json: @post.errors, status: :unprocessable_entity
  55. end
  56. end
  57. # DELETE /posts/1
  58. def destroy
  59. @post.destroy!
  60. end
  61. private
  62. # Use callbacks to share common setup or constraints between actions.
  63. def set_post
  64. @post = Post.find(params.expect(:id))
  65. end
  66. # Only allow a list of trusted parameters through.
  67. def post_params
  68. params.expect(post: [ :title, :body ])
  69. end
  70. end