I am sending a POST request to my Rails API with the following params:
"user"=>{"first_name"=>"Gerry", "last_name"=>"Moen", "email"=>"gerrymoen@test.com", "addresses"=>[{"address_type"=>"home"}, {"address_line_1"=>"25609 Littel Island", "address_line_2"=>nil, "city"=>"Chill", "state"=>"CA", "zip"=>"12345", "address_type"=>"mailing"}]}
However when I check the params in my API endpoint they appear like so:
"user"=>{"first_name"=>"Gerry", "last_name"=>"Moen", "email"=>"gerrymoen@test.com", "addresses"=>[{"address_type"=>"home", "address_line_1"=>"25609 Littel Island", "address_line_2"=>nil, "city"=>"Chill", "state"=>"CA", "zip"=>"12345"}, {"address_type"=>"mailing"}]}
As you can see the mailing address fields are sent as part of the home address. Now I know nested attributes are supposed to be assigned as addresses_attributes
. I have this in my user_params method to handle that.
params[:user][:addresses_attributes] = params.dig(:user).delete(:addresses)
params.require(:user).permit(....)
But my question is what is Rails doing behind the scenes to switch around my address attributes like that. I don't see anything apparent in my code that is doing that.
EDIT: Ok found some things. I printed out the unaltered POST data. It looked like this
"user[first_name]=Gregorio&user[last_name]=Douglas&user[email]=gregoriodouglas%40test.com
&user[addresses][][address_type]=home&user[addresses][][address_line_1]=458%20Karlene%20Greens&user[addresses][][address_line_2]=&user[addresses][][city]=Superior&user[addresses][][state]=MT&user[addresses][][zip]=59872&user[addresses][][address_type]=mailing"
I believe the reason why it was conflating the addresses was because they were sent as an array of hash attributes. I believe in order to get them correctly assigned I'd need to set an index in the array. Or something.