dennismonsewicz
dennismonsewicz

Reputation: 25542

Grape Rails API causing AASM to run for GET requests

Here is my AASM

  aasm column: :status do
    state :pre_approval, initial: true
    state :pending
    state :opened
    state :closed

    event :approved do
      transitions from: :pre_approval, to: :pending, guard: :approved?
    end

    event :received, after: Proc.new { set_received_date } do
      transitions from: :pending, to: :opened
    end

    event :complete, after: Proc.new { set_completion_date } do
      transitions from: :opened, to: :closed
    end
  end

Here is my new API

module ServiceRequests
  class API < Grape::API
    version 'v1', using: :path
    format :json

    resource :companies do
      params do
        requires :company_id, type: Integer, desc: "A Company Id"
      end

      route_param :company_id do
        resource :service_requests do
          get do
            Company.find(params[:company_id]).service_requests
          end
        end
      end

    end

  end
end

Here is the error I am receiving: AASM::InvalidTransition (Event 'approved' cannot transition from 'pending'):

I can log into the rails console and run Company.first.service_requests and it works perfectly and inside the application it runs when I hit the service_requests_path, so I'm not sure why this API call is causing issues

Upvotes: 0

Views: 180

Answers (1)

user473305
user473305

Reputation:

It looks like you must have a Company defined with a service_request whose state is pending yet is receiving another approved event. Your state machine doesn't define what should happen when a pending request is re-approved, though, which is why you're seeing that error message.

Find that company and the source of the event (does Company.service_requests fire any?) and you'll have found your problem. I don't think the problem is with your API class itself.

Alternatively, if you're absolutely certain there's no harm in a company's service request being approved multiple times, you could potentially work around the problem by changing the definition of the approved event to

event :approved do
  transitions from: [:pre_approval, :pending] to: :pending, guard: :approved?
end

One final thought: It looks like you have both approved (the event) and approved? (an accessor) defined as methods on service_request. Check to make sure you're not inadvertently advancing the state somewhere by calling approved when you really meant to call approved?.

Upvotes: 1

Related Questions