Avoiding exceptions in views

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.

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!!:wink:


Phlip

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs