Use your hacksaw and cut the nails off of
the 1 gang plastic nail-on box. drive the nails thru the box near the back corners top and bottom to attach it to the stud. The box must be room temperature or it will shatter.
This will allow you to extend the box out as far as you want. If it is 2 gang you can attach it with drywall screws from inside the box. Some people may have a problem with this method as far as U.L. but it works great.