Ronaldo, who netted three against Sevilla, opened the scoring early on and then Gareth Bale set up further goals for Karim Benzema and Ronaldo again as Madrid stormed into a 3-0 lead after 48 minutes.
However, Carlo Ancelotti's men were then stunned as Rayo won, and converted, two penalties in three minutes from Jonathan Viera to set up a thrilling final half-hour in which the home side hit the woodwork and came close on a number of other occasions.
They could not find an equaliser though and remain rooted to the foot of the table while Madrid stay within sight of Barca, who beat Espanyol on Friday in their own derby.
"Rayo Vallecano put us in trouble because they pressed well. We did not suffer in the first half, but we did in the second half. In the first half we scored two fantastic goals on the counter and had control but the second half was a disaster," conceded Ancelotti.
For the big stories and the banter follow us on Twitter: @tribalfootball