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 ||= [];
end

def self.column(name, sql_type = nil, default = nil, null = true)
columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default,
sql_type.to_s, null)
end

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

In app/models/post.rb

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

In script/console

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


Reference Links:

http://stackoverflow.com/questions/315850/rails-model-without-database/
http://railscasts.com/episodes/193-tableless-model
http://agilewebdevelopment.com/plugins/activerecord_base_without_table

Advertisements

1 Comment »

  1. Great!

    Comment by shivisngh — September 17, 2010 @ 3:08 pm


RSS feed for comments on this post. TrackBack URI

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

%d bloggers like this: