3

So, I have this system Im working on using rails 4 and Grape Api. Basically it aggregates information about maintenance services executed on vehicles. My models are defined like this:

# service.rb

class Service < ActiveRecord::Base
  has_many :service_items


#service_item.rb

class ServiceItem < ActiveRecord::Base
  belongs_to :service

Im implementing a API so external applications could post services on my system. Each service has a list of 1 or more service items associated. I have a route like: example.com/api/v1/services for POST. My question is how can I make this to accept a post with the service attributes, and service_items attributes nested with it?

I read Grape docs and started something like this:

#service_providers_api.rb

resource :services do
    desc "Post a Service"
    params do
      #requires :category_id, type: Integer
      requires :description, type: String
      requires :plate, type: String
      requires :mileage, type: Integer
      requires :date, type: Date
      optional :cost, type: BigDecimal

      requires :service_items do
         requires :description, type: Integer

      end
    end

    post do
      .
      .
      .
    end

 end

But Im not sure how I can mount the post data for this to work. Is it possible to make all this in a single request like so, or do I have to make each request separated? e.g. one POST to receive the service, then a series of POSTs for every service_item associated. What is the best approach recommended in this scenario?

1 Answer 1

7
params do
  requires :service_items, type: Hash do
    requires :description, type: Integer
  end
end

requires takes two param, you must provide a type. in your case a Hash

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.