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.
 
 
 
 
 
 

50 lines
1.3 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. render json: post.as_json.merge(image_url: (
  24. if post.image.attached?
  25. Rails.application.routes.url_helpers.rails_blob_url(post.image, only_path: true)
  26. else
  27. nil
  28. end)), status: :created
  29. else
  30. render json: { errors: post.errors.full_messages }, status: :unprocessable_entity
  31. end
  32. end
  33. private
  34. def set_thread
  35. @thread = Topic.find(params[:thread_id])
  36. end
  37. def post_params
  38. params.permit(:name, :message, :password, :image).transform_values { |v|
  39. v.presence
  40. }
  41. end
  42. end