Not sure how to reattach two bathroom objects
what is that called?

The true name is escutcheon, the common name is pipe flange or trim flange. Those escutcheons are typically designed to gently grip the pipe with small bendy metal tabs that are part of the escutcheon. Other (better quality) ones have a set-screw that holds them to the pipe. The bendy tabs on yours are probably now ineffective and your only options are to either remove and replace or try to get it to stick to the wall with some strategically placed globs of caulk and tape to hold it till cured.

Do I need to hammer a nail into that molding to get it to stay against the wall and spackle/paint over the nail?

Yes, that is exactly what you need to do.