In 1037, Muhammad ibn Rustam strengthened the defenses of Isfahan to protect it from the plundering Turkmen nomads from Khorasan. In 1041, after the defeat of the Ghaznavids by the Seljuqs at the battle of Dandanaqan, the Seljuqs became neighbors with the Kakuyids. After defeating the Ghaznavids, their leader, Tughril, made Ray the capital of his kingdom.