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

101 lines
2.8 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. # TODO: current_user.role が 'admin' もしくは 'member' でなければ 403
  33. title = params[:title]
  34. unless title.present?
  35. # TODO:
  36. # 既知サイトなら決まったフォーマットで,
  37. # 未知サイトならページ名をセットする.
  38. end
  39. post = Post.new(title: title, url: params[:url], thumbnail_base: '', uploaded_user: current_user)
  40. if params[:thumbnail].present?
  41. post.thumbnail.attach(params[:thumbnail])
  42. else
  43. # TODO:
  44. # 既知ドメインであれば,指定のアドレスからサムネール取得,
  45. # それ以外なら URL のスクショ・イメージをサムネールに登録.
  46. end
  47. if post.save
  48. if params[:tags].present?
  49. tag_ids = JSON.parse(params[:tags])
  50. post.tags = Tag.where(id: tag_ids)
  51. end
  52. render json: post, status: :created
  53. else
  54. render json: { errors: post.errors.full_messages }, status: :unprocessable_entity
  55. end
  56. end
  57. def viewed
  58. return head :unauthorized unless current_user
  59. current_user.viewed_posts << Post.find(params[:id])
  60. head :no_content
  61. end
  62. def unviewed
  63. return head :unauthorized unless current_user
  64. current_user.viewed_posts.delete(Post.find(params[:id]))
  65. head :no_content
  66. end
  67. # PATCH/PUT /posts/1
  68. def update
  69. if @post.update(post_params)
  70. render json: @post
  71. else
  72. render json: @post.errors, status: :unprocessable_entity
  73. end
  74. end
  75. # DELETE /posts/1
  76. def destroy
  77. @post.destroy!
  78. end
  79. private
  80. # Use callbacks to share common setup or constraints between actions.
  81. def set_post
  82. @post = Post.find(params.expect(:id))
  83. end
  84. # Only allow a list of trusted parameters through.
  85. def post_params
  86. params.expect(post: [ :title, :body ])
  87. end
  88. end