Adding a Virtual Attribute to a Model

It is possible to specify and define an additional attribute to a database model based on attributes that already exist. For example, if the Movie model has title and year attributes, you might want to create a new attribute called ext_title, which combines the title and year into one string.

The ext_title could be created by inserting the following code into the Movie class definition:

   def ext_title
      "#{title} (#{year})"
   end

Once defined, if m is a Movie object for Jaws (year --> 1975), the ruby expressions m.ext_title would have the value Jaws (1975).

Added attributes such as ext_title are called virtual attributes since they do not actually exist in the database table.