Ruby on Rails, return 0 instead of error -


i'm building ruby on rails application , i'm meet error:

typeerror: nil can't coerced float 

or string or other variables type when calculation or queries such as:

 upcoming = appointment.where(:hairdresser_id => hairdresser_id).where('status = ? or status = ?', 'accepted', 'personal').map{|app| app.price}.reduce(0, :+) 

i think understand problem, know if there simple way can return 0 instead of errors that, because happens maybe hairdresser not have accepted appointments.

one solution check if exists before doing caluclation i'm sure won't best solution!

thanks help!

if appointment#price db column can add additional check:

.where.not(price: nil) 

if it's method or virtual attribute either convert value float or int, convert nil it's numeric representation of 0:

.map{ |app| app.price.to_f } # or `app.price.to_i` 

or compact result of map, removes entries result nil

.map{ |app| app.price }.compact 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -