Ruby on Rails Tips

Ruby (Rails) constant lookup precedence

Recently I’ve been running into an interesting problem (at least, to me). Within a web application I am working on I found what I thought was a sporadic error occurring, which resulted in the need to restart Apache in order to temporarily fix it. That was, until I made a change to the controller and thus the issue appeared again, until I restarted Apache. The error:

uninitialized constant Frontend::User::ForgottenPasswordController::User

This puzzled me for quite a while, but I continued to develop while every now and again I would come up against this and look for answers. I found nothing, but knew the following:

  • User constant (model class) exists and works fine
  • This only happened in specific controllers

Jumping onto and having a chat with `workmad3` we solved the problem, and it’s a pretty simple one, once you understand how Ruby and thus Rails references constants. Continue reading