This is the approach I have used in the past:
In the application /models/tableless.rb
class Tableless < 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 the application /models/foo.rb
class Foo < Tableless column :bar, :string validates_presence_of :bar end
In script / console
Loading development environment (Rails 2.2.2) >> foo = Foo.new => #<Foo bar: nil> >> foo.valid? => false >> foo.errors => #<ActiveRecord::Errors:0x235b270 @errors={"bar"=>["can't be blank"]}, @base=#<Foo bar: nil>>
John Topley Nov 25 '08 at 21:22 2008-11-25 21:22
source share