I used to get bad leg cramps during or after club rides, 20-40 miles in length.
Then I started doing randonneuring, rides of 120 miles or longer. The first time I cramped 40 miles into a 400km (260 mile) ride, I thought I was going to DNF but didn't have a ride back to the start so I carried on albeit slower. 10 miles later I was just fine, cruising at normal speed. No pickle juice, bananas, electrolyte tables, biting my lower lip, etc. Shocked me, to be honest. I finished just fine.
My strategy now is, if a muscle starts feeling crampy, I change my posture or pedal stroke a bit, back off a bit, and carry on. I seem particularly susceptible to inner thigh cramping on climby routes. For those I pull my knees closer together, and that seems to help. If it goes into a full-on cramp, I say "shut the **** up, I'm not doing a damn thing for you" and carry on, with whatever weird body position reduces the pain. That seems to do the trick, and after it's gone I might be good for another 100 miles. True story.
I have no explanation, but I don't really care.