views:

51

answers:

2

I am creating a report which looks for the number of emails sent during a period of time:

I display it in the View as follows:

<td><%= @emails_sent.size %></td>

And it is generated in the Controller as follows:

   @sent_emails = ContactEmail.all(:conditions => ['date_sent >= ? and date_sent <= ?', @monday, @friday])

But sometimes now emails have been sent, which makes it nil, which causes the View to bonk.

What is the way to address this so that "nil" when the .find method comes up with nothing goes to a 0 instead of thinking it is 'nil?

+2  A: 

Can't you just do

@sent_emails = ContactEmail.all(:conditions => ['date_sent >= ? and date_sent <= ?', @monday, @friday]) || 0
neutrino
I had that it and it wasn't working....
Angela
oh, I had different error, so maybe that would work -- good that's what I was hoping would work.
Angela
The `all` method returns an empty array when no data is found. Hence @sent_emails will not be set to 0 under no circumstances.
KandadaBoggu
thanks you are right, that's what is happening!
Angela
+2  A: 

Hi Angela,

When you are using @neutrino solution it might give you an error (if the select is null) as in your view you call

<%= @emails_sent.size %>

reason is if the selection is nil, it returns a '0' , but in your view you are expecting an array

you have two options

1 - modify @neutrino code slightly

@sent_emails = ContactEmail.all(:conditions => ['date_sent >= ? and date_sent <= ?', @monday, @friday]) || []

** NOTE the [] instead of 0

2 - Get the count from the sql itself and get rid of the .size in view

cheers

sameera

Update - changed Array.new to [] #thanks @gertas

sameera207
`|| []` looks better
gertas
@ertas, cool, I'll update my post
sameera207