Img source: agilewarrior.wordpress.com

You may need attributes in your views or in your JSON response which may not be part of your models. In these situations, you may use virtual attributes that you may only use in your particular cases, and not bother to add many new attributes in your database table that are not that much relevant for that model.

Let’s say that you have a User model and you want to display a user’s full name, but you do not want to add this as a new attribute. You simply want to have a first_name, father_name and surname field that belong to the User, but want to have full_name as a virtual attribute.

We can have an attribute writer, or setter as it is commonly called for this full_name attribute:


def full_name=(name)
  full_name = name.split(' ', 3)
  self.first_name = full_name.first
  self.father_name = full_name.second
  self.last_name = full_name.last
end

We should also implement the attribute reader, or getter method:


def full_name
 [first_name, father_name, last_name].join(' ')
end

Now, we can call this virtual attribute from any User object that we want.