# Avoiding exceptions in views

**URL:** <https://www.ruby-forum.com/t/avoiding-exceptions-in-views/146715>\
**Category:** Rails\
**Created:** [August 24, 2008, 3:45pm UTC](https://www.ruby-forum.com/t/avoiding-exceptions-in-views/146715 "2008-08-24T15:45:10Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![fox](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/c5a1d2/32.png) [@fox](https://www.ruby-forum.com/u/fox)\
**Post date:** [August 24, 2008, 3:45pm UTC](https://www.ruby-forum.com/t/avoiding-exceptions-in-views/146715/1 "2008-08-24T15:45:10Z")

</div>

when rendering a view, if the object being rendered doesn’t respond to a  
method it raises an error message.  
For example, I have an Employee class and each employee has many Tasks.  
So I may call:  
\<%= employee.tasks.first.task\_name %\>

If, for some reason an employee has 0 tasks associated with it, the  
above template method would raise an exception.  
Is it efficient to loop through the @employees array, with something  
like:

@employees = Employee.find(:all,…).collect{|e| e if e.tasks.size \>  
0}.compact

or is there a better way?

thanks for reading.

---

<div class="post-metadata">

**Author:** ![fox](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/c5a1d2/32.png) [@fox](https://www.ruby-forum.com/u/fox)\
**Post date:** [August 24, 2008, 7:18pm UTC](https://www.ruby-forum.com/t/avoiding-exceptions-in-views/146715/2 "2008-08-24T19:18:19Z")

</div>

Oliver F. wrote:

> \<%= employee.tasks.first.task\_name %\>
> 
> If, for some reason an employee has 0 tasks associated with it, the  
> …  
> @employees = Employee.find(:all,…).collect{|e| e if e.tasks.size \>  
> 0}.compact

Your controller is not controlling your view enough! To present only  
employees  
with tasks, try this abomination:

Employee.find(:all).select{|e| e.tasks.any? }

That’s the same as yours, but it uses select.

If that melts your database server, try some variation on:

Employee.find(:all, :include =\> :tasks,  
:conditions =\> ‘tasks.id is not null’)

There might be better or alternate ways. Another one is this:

\<%= (employee.tasks + [Task.new]).first.task\_name %\>

Then at least the .first-ed array always has a blank Task on the end  
with a  
blank .name. You didn’t specify if your view should view taskless  
employees.  
(And shame on them for slacking!!😉

–  
Phlip
