Max Al Farakh
Max Al Farakh

Reputation: 4476

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.

Upvotes: 9

Views: 2267

Answers (2)

dnch
dnch

Reputation: 9605

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

Upvotes: 4

d11wtq
d11wtq

Reputation: 35298

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.

Upvotes: 8

Related Questions