Ruby: Throwing undefined method error -


running statement this:

self.user.email || self.organization.email || nil 

ruby throws error undefined method 'email' nil:nilclass, should return nil instead. doing wrong here?

does occur because in cases user || organization nil?

in self.user.email, if self.user nill, can't call email on it.

if you're using ruby 2.3 or newer, can use safe navigation operator:

self.user&.email || self.organization&.email 

note || nil @ end unneccesary.

if don't want introduce dependency ruby 2.3 or newer, use object#try activesupport (included rails):

self.user.try(:email) || self.organization.try(:email) 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -