[V23] Rails3 backporting to Rails2

rebased #510.