Hi Friends,
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:
schema.rb
ActiveRecord::Schema.define(:version => 1) do
create_table "details", :force => true do |t|
t.string "card_id"
t.integer "expiration_month"
t.integer "expiration_year"
end
end
detail.html
<%= f.text_field :expiration_month %s>
<%= f.text_field :expiration_year %>
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.
detail.html
<%= f.text_field :expiry %> //Format would be mm/yyyy
detail.rb
def expiry
[expiration_month, expiration_year].join(' ')
end
def expiry=(exp)
split = exp.split('/', 2)
self.expiration_month = split.first
self.expiration_year = split.last
end
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.
acceptance:
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"
Example:
class Blog < ActiveRecord::Base
validates :terms_of_service, acceptance: true
end
confirmation:
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.
Example:
class Blogger < ActiveRecord::Base
validates :password, confirmation: true
validates :email_confirmation, presence: true
end
And the view will be like:
<%= text_field :blogger, :password %>
<%= text_field :password, :password_confirmation %>
0 Comment(s)