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.
 
 
 
 
 
 

53 lines
1.4 KiB

  1. class ThreadPostsController < ApplicationController
  2. before_action :set_thread
  3. # GET /api/threads/:thread_id/posts
  4. def index
  5. sort = params[:sort].presence_in(['created_at', 'score']) || 'created_at'
  6. order = params[:order].presence_in(['asc', 'desc']) || 'desc'
  7. posts = @thread.posts
  8. .select('posts.*, (good - bad) AS score')
  9. .order("#{ sort } #{ order }")
  10. render json: posts.map { |post|
  11. post.as_json.merge(image_url: (
  12. if post.image.attached?
  13. Rails.application.routes.url_helpers.rails_blob_url(post.image, only_path: true)
  14. else
  15. nil
  16. end))
  17. }
  18. end
  19. # POST /api/threads/:thread_id/posts
  20. def create
  21. post = @thread.posts.new(post_params)
  22. if post.save
  23. post.thread.tap { |thread|
  24. thread.updated_at = post.created_at
  25. }.save!
  26. render json: post.as_json.merge(image_url: (
  27. if post.image.attached?
  28. Rails.application.routes.url_helpers.rails_blob_url(post.image, only_path: true)
  29. else
  30. nil
  31. end)), status: :created
  32. else
  33. render json: { errors: post.errors.full_messages }, status: :unprocessable_entity
  34. end
  35. end
  36. private
  37. def set_thread
  38. @thread = Topic.find(params[:thread_id])
  39. end
  40. def post_params
  41. params.permit(:name, :message, :password, :image).transform_values { |v|
  42. v.presence
  43. }
  44. end
  45. end