off the rails. (idiomatic) In an abnormal manner, especially in a manner that causes damage or malfunctioning. (idiomatic) Insane. (idiomatic) Off the intended path. (idiomatic) Out of control.
Used figuratively for thinness from 1872. To be “off the rails” in a figurative sense is from 1848, an image from the railroads. In U.S. use, “A piece of timber, cleft, hewed, or sawed, inserted in upright posts for fencing” [Webster, 1830].
In an abnormal or malfunctioning condition, as in “Her political campaign has been off the rails for months”. The phrase occurs commonly with go, as in “Once the superintendent resigned, the effort to reform the school system went off the rails”. This idiom alludes to the rails on which trains run; if a train goes off the rails, it stops or crashes. [Mid-1800s]
sources: Google, Wiktionary, Cambridge English