开发者

Return value of another attribute if needed attribute is nil

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜