If you get
NoMethodError is occurred.
# user is nil name = user.name # NoMethodError !!!!1
You had better use
You can get
name value if
user is not
nil and if
user is nil you can get ‘nil’ instead.
NoMethodError is not occurred.
# user is nil name = user.try(:name) # return nil. not occurred NoMethodError # user is not nil name = user.try(:name) # return name value.
You can set default value if user is nil like this.
name = user.try(:name) || "default name"