Tuesday, May 19, 2009

Rails - Dealing with nil in views

I've been working on the task management application and after creating my initial databases and views started to make the UI more friendly. Each task in the application has an owner. I'm doing this with two tables, one called tasks and one called users. The task table has a reference to the user called user_id. When you pull the task index view you end up seeing the ID reference instead of the person's name. That's not too helpful.
My first attempt was to put code like this in the view:

in view/index.html.erb


Owner:
<%=h User.find(@task.user_id).name %>



The problem is when the user_id doesn't have a value or the value is not valid. Lots of ways to solve this, like add a validation when a task is created that says it exists, but what if you want to make the task but don't know who should own it yet? And what if you delete a person, because they leave the company. Need some routine to reassign their tasks. But in any case, index shouldn't crash.
My first thought, and I think a bad one was to put exception logic in the view. As soon as I started typing, I knew that was bad.
So I came up with this simple solution in the model:

in model/task.rb
def owner
begin
User.find(self.user_id).name
rescue
"None"
end
end

Regardless of the reason for the crash its caught and index will keep working. It doesn't depend on other routines to make sure this piece of code doesn't fail. Best of all, you could write a test on this too. Not a big deal here, but if it got more complex you might want it.
The view is much more readable like this:
<%=h @task.owner %>

One last thing I think I should do is log something in the exception. That assumes someone would notice a problem in the log, but its not a bad practice.

If you have a better way to resolve this, let me know.

No comments:

Post a Comment