Skip to content

Returns array for hash parameter when not present #1596

Closed
@nicooga

Description

@nicooga

Using grape 0.19.1, also hapening in 0.19.0.

Whats happening

Given I declared a parameter key with type Hash and the parameter was not included when calling the controller, I't returns an empty array for that key.

Expected behavior

It should return an empty hash, or nil, or perhaps not include the key in the parsed output.

Extended Explanation

Given this parameters:

params do
  with coerce: String do
    optional :avatar
    optional :first_name
    optional :last_name
    optional :school_year
    optional :phone_number
    optional :age
    optional :description
  end

  optional :location_attributes, type: Hash, default: {} do
    optional :city
    optional :district
    optional :street
    optional :street_number
    optional :notes
  end
end

... when I hit the controller with this params:

{"user"=>
  {"id"=>288,
   "avatar"=>
    "http://localhost:3000/system/users/avatars/000/000/288/original/profile_pic.jpg?1489450290",
   "first_name"=>"Numbers",
   "last_name"=>"Terry",
   "age"=>nil,
   "description"=>nil,
   "school_year"=>nil,
   "phone_number"=>nil,
   "email"=>"teacher@gmail.com",
   "teaches_online"=>false,
   "teaches_at_own_place"=>false,
   "teaches_at_public_place"=>true,
   "teaches_at_students_place"=>false,
   "is_teacher"=>true,
   "is_student"=>false},
 "id"=>"288",
 "location_attributes"=>{}}

... and I extract the declared params like this:

attributes = declared params[:user]

the result is this:

attributes #=>
{"avatar"=>
  "http://localhost:3000/system/users/avatars/000/000/288/original/profile_pic.jpg?1489450290",
 "first_name"=>"Numbers",
 "last_name"=>"Terry",
 "school_year"=>nil,
 "phone_number"=>nil,
 "age"=>nil,
 "description"=>nil,
 "location_attributes"=>[]}

Note that location_attributes gets parsed into an empty array. I do not know exactly what is the expected behavior, but an empty array is not what I've expected. I'd either have nil or an empty hash. It breaks with activerecord's accepts_nested_attributes_for :location with:

NoMethodError (undefined method `with_indifferent_access' for #<Hashie::Array []>)

I am missing something obvious here?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions