A ratchet contains a gear with two step levers called "pawls" that are spring-loaded. It uses one lever at a time for each direction, which allows it to catch the teeth and spring into a groove, making it to go one way and not go backwards (if you have ever looked at a zip tie, this is the same mechanism). As you turn the ratchet to tighten what you are working on, the lever is wedged into the gear, keeping it still as you turn to tighten. When you move the ratchet back the other way and hear a clicking noise, the lever releases the gear so that you can go back without loosening what you are working on (see Resources below).
A Ratchet Mechanism
A ratchet has a button or lever on it that switches the step lever on the gear to the other side, making it go the other way so that it works to loosen instead of tighten.
These use the same mechanism as hand ratchets, only they are used with motors for various applications. There's an automatic switch to switch it back and forth for loosening and tightening. Automatic ratchets are used in roller coaster safety tracks and winches, as well as numerous other applications.