Rats come for food, warmth and shelter. Take away cooked food, meat and dairy, disturb the pile regularly, and put a physical barrier underneath. Those three between them solve almost every case. Below: what causes rats in compost, how to fix it today, and how to stop it happening again.
Rats in compost.
Why a pile attracts them
It is warm, dry in the middle, undisturbed, and sometimes contains high-value food. A neglected bin in a quiet corner is close to ideal habitat, whatever you put in it.
What actually works
No cooked food, meat, fish, dairy or oil. The single biggest factor.
Turn it regularly. Rats want undisturbed. A pile forked over weekly is unattractive to them.
Hardware cloth underneath. 6mm galvanised mesh under and around the base, if rats are established locally. Chicken wire is too coarse. They get through it.
Keep it damp. A wet pile is a poor nest.
What does not work
Ultrasonic devices, peppermint oil, and most folk deterrents have no reliable evidence behind them. Poison near a compost pile risks secondary poisoning of owls, foxes and pets, and does not address why the rats came.
If they are already established: a sealed tumbler off the ground removes the habitat entirely, and is the one situation where a tumbler is clearly the right purchase.