dalibor (owner)

Revisions

gist: 228654 Download_button fork
public
Description:
Rails model without table
Public Clone URL: git://gist.github.com/228654.git
Embed All Files: show embed
Rails model without table #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#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>>