class ThreadPostsController < ApplicationController before_action :set_thread # GET /api/threads/:thread_id/posts def index sort = params[:sort].presence_in(['created_at', 'score']) || 'created_at' order = params[:order].presence_in(['asc', 'desc']) || 'desc' posts = @thread.posts .select('posts.*, (good - bad) AS score') .order("#{ sort } #{ order }") render json: posts.map { |post| post.as_json.merge(image_url: ( if post.image.attached? Rails.application.routes.url_helpers.rails_blob_url(post.image, only_path: true) else nil end)) } end # POST /api/threads/:thread_id/posts def create post = @thread.posts.new(post_params) if post.save render json: post.as_json.merge(image_url: ( if post.image.attached? Rails.application.routes.url_helpers.rails_blob_url(post.image, only_path: true) else nil end)), status: :created else render json: { errors: post.errors.full_messages }, status: :unprocessable_entity end end private def set_thread @thread = Topic.find(params[:thread_id]) end def post_params params.permit(:name, :message, :password, :image).transform_values { |v| v.presence } end end