[V40] Rails 3.1 porting

rebased #802.