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
精彩评论