This is a good video about contracts. It's targeted for designers, but I think most of it still applies to developers. I think the best point in the video, have a good lawyer.
And never ever ever start work without a contract in place!
Also, the magic words to avoid the described scenario are "intellectual property will transfer on receipt of payment". The parents video covers this in more detail.