Skip to content

Instantly share code, notes, and snippets.

@dalibor
Created November 7, 2009 11:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save dalibor/228654 to your computer and use it in GitHub Desktop.
Save dalibor/228654 to your computer and use it in GitHub Desktop.
Rails model without table
#In app/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 app/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>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment