Saving Users from Error id=”” not found.(Ruby On Rails)

David Molina
3 min readApr 19, 2021

As a new programmer, I am learning to welcome error pages, they point out the flaws in my program. With the provided information I get a chance to debug and learn. Those errors represent mental challenges meant to push my knowledge to its limits. It's akin to resistance training for athletes.(I imagine...) But when a user comes across an error they are usually frustrated and rightly so because there are some expectations that come when using an application.

There is a saying that goes, “Form follows Function”. It doesn't matter if the application is absolutely stunning if you aren’t able to use the basic functions of an application. I ran into a similar issue with my Rails Project, Classic Literature -> Yoda Translator. The main functionality is to allow a user-submitted timeless, cultural piece and read it as Jedi Master Yoda would. Simple enough, perhaps sacrilegious to fans of Classic Literature but I digress. Within the context of this app, a user should be able to add a new author, and a piece of classical literature. They should not be able to add a new category assuming that at this point we are aware of all the pieces of work available. Knowing this I set my route helpers to redirect a user to the appropriate page.

config/routes.rb file

The first four lines allow a user to use the first 3 parts of CRUD(Create, Read, and Update) on an object. Line two is an example of a nested route. Those worked fine, pretty straight forward setup. the issue came in line 4.

Sidenote: If a user decides they want to change the show page URL from (example.com/categories/1) to (example.com/categories/1asdfklj) you receive an error like this one:

With the way our routes.rb file is setup it will take anything typed after “categories/” as a search input for an ID. So if a crafty user wants to hack the application and attempt to add a new category we don’t want to greet them with this error. (No matter how ill-willed their attempts may be.) We want to send them in the right direction. But how do we do that? We can use a helper called [rescue_from]. The method below is essentially a catch can for any ActiveRecord::RecordNotFound errors.

You can create a custom helper, I named mine :record_not_found, and let the person know they are attempting to access a page they are not authorized to see. You can send an alert/message/error/etc. or send them to any page you would like but this rescues users from incorrectly typed id’s. Obviously, there are many other errors for a user to encounter but this was one that took forever for me to solve. I hope this helps anyone looking for ways to solve any errors they are experiencing while utilizing ActiveRecord’s abilities.

--

--