Search code examples
ruby-on-railsrubyapigrape-api

ruby-grape - requires method not working 3 levels deep


I am building an API right now using Grape and Rails. One endpoint takes POST requests for Orders. The architecture is as follows: An Order has_many OrderDetails. OrderDetails has_many OrderDetailCustomFields.

As such, I would expect that POST request JSON objects will have values nested three levels deep. My code looks as follows for my orders endpoint: (bare in mind I have gotten rid of most of the other fields, so those who help me can look at just the nesting of parameter requirements)

params do 
    requires :order, :type => Hash do
        requires :order_details, :type => Array do
            requires :order_detail, :type => Hash do
                requires :cost, type: Integer#, desc:
                requires :quantity_ordered, type: Integer#, desc:
                requires :item_id, type: Integer#, desc:
                optional :order_detail_custom_fields, :type => Array do
                    optional :order_detail_custom_field, :type => Hash do
                        requires :field_name, type: String#, desc:
                        optional :field_value, type: String#, desc:
                    end
                end
            end
        end
    end
end

I have other endpoints that have optional arrays and optional hashes. If nested fields in those optional arrays or hashes are required, Grape will typically ONLY throw an error if the parent parameter exists in the request.

However in the case of :order_detail_custom_field that is not the case. As soon as I go from from 2 parameter levels deep to 3 parameter levels deep, Grape barks at me and seems to make the entire :order_detail_custom_field Array required for all :order_details Hashes. Even though it is optional. Other :order_detail hashes that do not have custom_fields now get errors stating that they require :field_name for :order_detail_custom_field.

The exact error is:

  {
error:  order[order_details][order_detail][order_detail_custom_fields][order_detail_custom_field][field_name] is missing
}

The only difference I can see is that the errors seem to be happening to parameters that are 3 levels deep rather than 2 levels deep. Does anyone have experience with this? Or am I overlooking something?


Solution

  • For anyone who stumbles upon this question, I have submitted a github issue which has been marked as "bug?". As far as I know this issue is still happening as per @JGonzalesD.