Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grape api - How to POST nested resources?

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?

like image 480
Fabiano Arruda Avatar asked Dec 04 '25 03:12

Fabiano Arruda


1 Answers

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

like image 127
David Chan Avatar answered Dec 06 '25 17:12

David Chan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!