Search code examples
ruby-on-railsstrong-parameters

ParameterMissing when a parameter is empty in Rails


In my API I have an endpoint at /api/orders

When doing a POST call with the following JSON:

{"order":{}}

I get a ActionController::ParameterMissing: param not found: order

My strong parameters function looks like this:

def order_params
  params.require('order')
end

Why is not letting me pass an empty 'order', if I do:

{"order":{"test":"value"}}

It works fine.


Solution

  • Because this is how .require works. See the API: http://edgeapi.rubyonrails.org/classes/ActionController/Parameters.html#method-i-require

    Rails isn't ensuring that the key exists but, rather, that there are parameters .present? for this key.

    The source for .require helps elucidate this:

    # File actionpack/lib/action_controller/metal/strong_parameters.rb, line 182
    def require(key)
      self[key].presence || raise(ParameterMissing.new(key))
    end
    

    And {}.present? # => false.