We have talked about few Rails topics earlier like validates associated and overriding naming convention of table names. Here I am again with one more topic Virtual Attributes in Rails. Before discussing that lets look into a situation where you want that a person needs to accept terms and condition to go to the next action or you want a little change in your form submission method and don't want to change table for that. Lets take example of Details table, where you have fields like expiration_month and expiration_year and your schema and view was something like:
ActiveRecord::Schema.define(:version => 1) do
create_table "details", :force => true do |t|
Now you want to use only a single field where you can determine expiration month and year in a single field (i.e. expiry) in mm/yyyy format.
This kind of requirement can be achieved through virtual attributes in rails.
Virtual Attributes is a feature in rails that allows you to create form fields which may not relate to database.
To achieve this we will do these changes in our detail.html and detail.rb file.
<%= f.text_field :expiry %> //Format would be mm/yyyy
[expiration_month, expiration_year].join(' ')
split = exp.split('/', 2)
self.expiration_month = split.first
self.expiration_year = split.last
Now as you have basic idea of virtual attributes lets look at some major use cases of it, that are used very commonly in rails.
As I told earlier virtual attributes are used in the condition where we don't want its existence in DB so acceptance is used basically as a check-box where you want that user must check to go to the next action. Basically used for agree on terms and conditions. The default error message for this helper is "must be accepted"
class Blog < ActiveRecord::Base
validates :terms_of_service, acceptance: true
It is also a use case of virtual attributes as whenever there is a condition where you have same content in two fields. as Confirmation Email or Confirmation Password. So it creates a virtual attribute for confirmation that doesn't have existence in DB.
class Blogger < ActiveRecord::Base
validates :password, confirmation: true
validates :email_confirmation, presence: true