The return value of another attribute if the nil attribute is required

I have a model Userthat has attributes fullnameand email.

I need to somehow rewrite the method fullnameso that it returns a value emailwhen it fullnameis zero or empty.

+5
source share
2 answers

I have not tried it using ActiveRecord, but does it work?

class User < ActiveRecord::Base
  # stuff and stuff ...

  def fullname
    super || email
  end
end

It depends on how ActiveRecord is blended in these methods.

+6
source

To do what you want, you can easily override the default reader for fullnameand 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
+3
source

All Articles