Advertisement
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 :set_receiverable, only: :create
- 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 if params[:receiverable].blank? || !params[:receiverable].is_a?(Array) || params[:receiverable].any?(Hash)
- # receiverables = @sender.find_by_resource_id_and_resource_type(params[:receiverable_id], params[:receiverable_type])
- if params[:message][:receiverable_type].blank? || params[:message][:receiverable_id].blank?
- return
- else
- receiverable_type = params[:message][:receiverable_type]
- receiverable_id = params[:message][:receiverable_id]
- end
- receiverables = receiverable_type.classify.constantize.where(id: receiverable_id)
- create_errors = []
- receiverables.each do |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
- p "@sender: #{@sender}"
- end
- def message_params
- params.require(:message).permit(:receiverable_id,
- :receiverable_type,
- :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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement