Virtual attributes are handy for those instances where you want to add an attribute to your view (like a checkbox), but don’t want it persisted as part of your model.

For example say we want a confirmation checkbox (attibute :password_checked), but don’t want it included as part of our model and saved to the database.

To add a virtual attribute to your model add it as a attr_accessor and then make it accessible with the attr_accessible attribute.

class User < ActiveRecord::Base
  attr_accessor           :password_checked
  attr_accessible         :password_checked

Just adding it as a attr_accessor automatically creates a virtual field.

You can then access this in your view like any other model attribute:

<div class="field">
  <%= f.label :email %><br />
  <%= f.text_field :email %>
<div class="field">
  <%= f.label :password %><br />
  <%= f.text_field :password %>
  <br />
  <%= f.check_box :password_checked %>
  <span class="small_label">Confirm password</span>

Then when you hit the submit button, you should see a request that looks like this in google developer tools.

Note: The checkbox has two values to deal with the HTML gotcha of check boxes.

Now you could start reacting to whether the check box is set in your controller by doing something like this:

class UsersController < ApplicationController
  def create
    logger.debug "checked value #{params[:user][:password_checked]}"
    if params[:user][:password_checked] == "1"
        # do something

But if it’s validation you want, it really belongs in the model. I’ll show you how to do that next.

For more information on attributes and accessors checkout:

Michael Hartl’s Rails book here and here.