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

98 lines
2.5 KiB

  1. require 'open-uri'
  2. require 'nokogiri'
  3. class PostsController < ApplicationController
  4. before_action :set_post, only: %i[ show update destroy ]
  5. # GET /posts
  6. def index
  7. if params[:tags].present?
  8. tag_names = params[:tags].split(',')
  9. match_type = params[:match]
  10. if match_type == 'any'
  11. posts = Post.joins(:tags).where(tags: { name: tag_names }).distinct
  12. else
  13. posts = Post.joins(:tags)
  14. tag_names.each do |tag|
  15. posts = posts.where(id: Post.joins(:tags).where(tags: { name: tag }))
  16. end
  17. posts = posts.distinct
  18. end
  19. else
  20. posts = Post.all
  21. end
  22. render json: posts.as_json(include: { tags: { only: [:id, :name, :category] } })
  23. end
  24. # GET /posts/1
  25. def show
  26. post = Post.includes(:tags).find(params[:id])
  27. viewed = current_user&.viewed?(post)
  28. render json: (post
  29. .as_json(include: { tags: { only: [:id, :name, :category] } })
  30. .merge(viewed: viewed))
  31. end
  32. # POST /posts
  33. def create
  34. return head :unauthorized unless current_user
  35. return head :forbidden unless ['admin', 'member'].include?(current_user.role)
  36. # TODO: URL が正規のものがチェック,不正ならエラー
  37. title = params[:title]
  38. post = Post.new(title: title, url: params[:url], thumbnail_base: '', uploaded_user: current_user)
  39. post.thumbnail.attach(params[:thumbnail])
  40. if post.save
  41. post.resized_thumbnail!
  42. if params[:tags].present?
  43. tag_ids = JSON.parse(params[:tags])
  44. post.tags = Tag.where(id: tag_ids)
  45. end
  46. render json: post, status: :created
  47. else
  48. render json: { errors: post.errors.full_messages }, status: :unprocessable_entity
  49. end
  50. end
  51. def viewed
  52. return head :unauthorized unless current_user
  53. current_user.viewed_posts << Post.find(params[:id])
  54. head :no_content
  55. end
  56. def unviewed
  57. return head :unauthorized unless current_user
  58. current_user.viewed_posts.delete(Post.find(params[:id]))
  59. head :no_content
  60. end
  61. # PATCH/PUT /posts/1
  62. def update
  63. if @post.update(post_params)
  64. render json: @post
  65. else
  66. render json: @post.errors, status: :unprocessable_entity
  67. end
  68. end
  69. # DELETE /posts/1
  70. def destroy
  71. @post.destroy!
  72. end
  73. private
  74. # Use callbacks to share common setup or constraints between actions.
  75. def set_post
  76. @post = Post.find(params.expect(:id))
  77. end
  78. # Only allow a list of trusted parameters through.
  79. def post_params
  80. params.expect(post: [ :title, :body ])
  81. end
  82. end