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
Post a Comment