I eat a balanced diet with plenty of fruit and veg, don't smoke, drink moderately (1 drink 3 days a week) work out regularly and still get these. The worst is in yoga, when my feet cramp and I can't do something. Calves in bed close second.
I thought it was from drinking or fasting but there seems no correlation. Age, maybe.
I did try taking magnesium- a few times over the years, but it gives me migraines. Like if I take it I wake up the next morning with a migraine. Which is considerably more painful than a leg cramp. Could look for foods with more of it, though, I guess. Good idea anyway, that is plausible.