Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class MessagesController < ApplicationController
- before_action :authenticate_role
- before_action :set_message, except: %i(index create)
- before_action :set_sender, except: :index
- before_action :autorize_action, only: %i(update destroy)
- def index
- messages = Message.where(status: params[:status]).recent if params[:status]&.in?(Message::statuses.keys)
- messages ||= Message.recent
- render json: messages
- end
- def create
- # return unless params[:receiverable].any? && params[:receiverable].is_a?(Array)
- return unless params[:receiverable].any? && params[:receiverable].is_a?(Array) && !params[:receiverable].any?(Hash)
- create_errors = []
- params[:receiverable].each do |receiver|
- # message = @sender.sended_messages.build(message_params.merge({receiverable: receiver}))
- message = @sender.sended_messages.build(message_params)
- message.receiverable = receiver
- unless message.save
- create_errors << { message: "An error occurred: #{message.errors.full_messages.join('; ')}" }
- end
- end
- render json: { errors: create_errors }, status: 422 if create_errors.any?
- end
- def update
- if @message.update(message_params)
- render json: @message, status: :ok
- else
- render json: { message: "An error occurred: #{@message.errors.full_messages.join('; ')}" }, status: 422
- end
- end
- def destroy
- @message.destroy
- render json: { status: :ok }
- end
- private
- def authenticate_role
- current_admin! || current_customer! || current_respondent!
- end
- def set_message
- @message = Message.find_by_id(params[:id])
- end
- def set_sender
- @sender = current_admin || current_customer || current_respondent
- end
- def message_params
- params.require(:message).permit(:receiverable, :status, :subject, :text)
- end
- def autorize_action
- unless current_customer == @message.senderable || current_respondent == @message.senderable || current_admin # admin_signed_in?
- return render json: { error: 'An unauthorized!' }, status: 401
- end
- end
- end
Add Comment
Please, Sign In to add comment