Rails virtual attribute

Virtual attributes are userful for those instances where we 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 :synchronous), 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 Import < ActiveRecord::Base
require ‘csv’
attr_accessible :error_file, :format, :import_date, :input_file, :status, :synchronous
attr_accessor :product_count, :variant_count, :sub_variant_count, :synchronous
  has_attached_file :input_file, PAPERCLIP_STORAGE_OPTIONS
has_attached_file :error_file, PAPERCLIP_STORAGE_OPTIONS.merge({:default_url=>”})

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:

= simple_form_for(@import, :html=>{:class=>’form-horizontal’}) do |f|

  = f.input :input_file, :as=>:file
  = f.input :import_date, :as=>:string, :input_html=>{:class=>’input-small’}
  = f.input :synchronous, :as=>:boolean

    = f.button :submit, ‘Upoad file’, :class=>’btn btn-primary btn-large’

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

def create
@import = Import.new(params[:import])

respond_to do |format|
if @import.save
if !@import.synchronous.nil? && @import.synchronous == ‘1’
flash[:notice] = ‘Import processed successfully’
flash[:notice] = ‘Import initiated’
format.html { redirect_to imports_path }
format.json { render json: @import, status: :created, location: @import }
format.html { render action: “new” }
format.json { render json: @import.errors, status: :unprocessable_entity }

This is quick look to virtual attributes.

2 thoughts on “Rails virtual attribute

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s