I've got a User
model which has fullname
and email
attributes.
I need to overwrite method fullname
somehow so it will return value of email
when fullname
is nil or empty.
I haven't tried it with ActiveRecord, but does this work?
class User < ActiveRecord::Base
# stuff and stuff ...
def fullname
super || email
end
end
It depends how ActiveRecord mixes in those methods.
To do what you want, you can quite easily override the default reader for fullname
and do something like this:
class User < ActiveRecord::Base
def fullname
# Because a blank string (ie, '') evaluates to true, we need
# to check if the value is blank, rather than relying on a
# nil/false value. If you only want to check for pure nil,
# the following line wil also work:
#
# self[:fullname] || email
self[:fullname].blank? ? email : self[:fullname]
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With