Showing posts with label begin rescue. Show all posts
Showing posts with label begin rescue. Show all posts

Wednesday, March 12, 2008

Begin Rescue Else End

So today I was working on a project. This project will be an admin interface for an application that has already been running for a while(which was written in PHP). So I am having to use a legacy database(tutorial coming soon for making admin interface for a legacy DB!) Anyway, I have an employee, and a department. The employee references which department he is in by the ID. However, some employees have an ID that is not used in the department table(department got deleted at some point, never existed, who knows?).


In my employee model, I am making a function to take the department id from the employee tables(thisdept), and look up the number in the department table to get the name of the department, all pretty standard stuff.


Here is what I tried first:



def deptname
dept = Department.find(thisdept)
dept.name
end



ActiveRecord::RecordNotFound in Employees#index

Showing vendor/plugins/active_scaffold/frontends/default/views/_list_record.rhtml where line #10 raised:

Couldn't find Department with ID=13


So we are going to need something along the lines of a try - catch. Ruby's equivalent is the begin-rescue-else-end. Begin is the code that might throw an error. Rescue is the code to excute if there is an error. Else is executed if there is no error. You can also add an ensure block, which will be run after everything, regardless. Here is my fix:




def deptname
begin
dept = Department.find(thisdept)
rescue
"No Department"
else
dept.name
end
end

Works like a charm! See you next time.