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

90 lines
2.5 KiB

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