简体   繁体   中英

if a value from controller is nil, how do I display 0?

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?

你不能这样做吗?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM