Veerasundaravel's Ruby on Rails Weblog

September 17, 2010

ActiveRecord – Tableless Model

If you want to create an ActiveRecord model without any table reference, and want to add validation for that model means, you can go with this example code.

In app/models/base_model.rb

class BaseModel < ActiveRecord::Base
def self.columns
@columns ||= [];

def self.column(name, sql_type = nil, default = nil, null = true)
columns <<, default,
sql_type.to_s, null)

# Override the save method to prevent exceptions.
def save(validate = true)
validate ? valid? : true

In app/models/post.rb

class Article < BaseModel
column :title, :string
validates_presence_of :title

In script/console

Loading development environment (Rails 2.2.2)
>> article =
=> #<Article title: nil>
>> article.valid?
=> false
>> article.errors
=> #<ActiveRecord::Errors:0x235b270 @errors={“title”=>[“can’t be blank”]}, @base=#<Article title: nil>>

Reference Links:

%d bloggers like this: