ActiveRecord tableless model gem

Written by Keith McDonnell. Last updated on Monday, January 31, 2011.

I’ve written a gem to simplify creating ActiveRecord clases which don’t need a database table. I’ve found this useful for:

Thanks to Ryan Bates Tableless Model Railscast and the Tableless Model asciicast for the inspiration.


$ gem install active_record-tableless_model


require 'active_record-tableless_model'

class Task < ActiveRecord::Base
  column :description,  :text
  column :priority,     :integer
  column :project_id,   :string  

Note that your class must still inherit from ActiveRecord if you need to use validations and associations.

How it works

If you create a class inheriting from ActiveModel, and no corresponding table exist in the database you’ll get an ActiveRecord::StatementInvalid error. You need to tell your model what columns should exist on the table. Migrations do this by defining colums using column.

All you need to do is create class methods allowing you to declare the column names directly in the class (without the need for a migration). Here’s how it’s done:

module TablelessModel
  def self.included(klass)
*  klass.extend ClassMethods
  module ClassMethods
*  def self.columns() @columns ||= []; end  
*  def self.column(name, sql_type = nil, default = nil, null = true)  
*    columns <<, default, sql_type.to_s, null)  
*  end  

There’s no need for this gem if you’re using Rails 3 – ActiveModel provides all ActiveRecord functionality for plain Ruby objects.

If you'd like to discuss this article, you can send me an email and/or publish an article online and link back to this page.