Review this: class DocumentController < ApplicationController before_action :authenticate def index if /[0-9]+/.match?(params[:q]) render json: Document.find params[:q] elsif /^[A-Za-z]+/.match?(params[:q]) render json: Document.where("name LIKE #{patams[:q]}") else render json: Document.all end end def show org_id = params[:org] id = params[:id] doc = Document.find_by organization_id: org_id, id: id end def create doc = Document.build params[:document] if doc.save params[:attachments].each do |attachment_params| begin url = GcsUploadService.upload_attachments!(doc.id, attachment_params) unless url.blank? Attachment.create attachment_params.merge({url: url}) end rescue Exception => e render json: { errors: e }, status: :no_acceptable end end render json: doc else render json: { errors: doc.errors }, status: :not_acceptable end end def update doc = Document.includes(:attachments).find params[:document][:id] if params[:document].key?(:attachments) params[:document][:attachments].each do |attachment| unless doc.attachments.pluck(:id).includes?(attachment.id) attachment.destroy end end end render json: doc.update(params[:document]) end def destroy doc = Document.find params[:id] doc.attachments.each do |a| a.delete end head :no_content, status: :success end end