Turn off the power to the circuit at the breaker, and verify power is off. Then pull the nails, and remove the box. Then install an old work braced ceiling box.
They are available at any hardware or big box home improvement store, from many different manufactures.
Those nails should not be inside the box, and replacing them will screws does not solve that problem.
National Electrical Code 2014
Chapter 2 Wiring Methods
Artical 314 Outlet, Device, Pull, and Junction Boxes; Conduit Bodies; Fittings; and Handhole Enclosures.
III. Construction Specifications
314.43 Nonmetallic Boxes. Provisions for supports or other mounting means for nonmetallic boxes shall be outside of the box, or the box shall be constructed so as to prevent contact between the conductors in the box and the supporting screws.