views:

3191

answers:

4

This came up a bit ago (http://stackoverflow.com/questions/399490) but it looks like the Rails plugin mentioned is not maintained (http://agilewebdevelopment.com/plugins/activerecord_base_without_table). Is there no way to do this with ActiveRecord as is?

If not, is there any way to get ActiveRecord validation rules without using ActiveRecord?

ActiveRecord wants the table to exist, of course.

Thanks!

+5  A: 

Validations are simply a module within ActiveRecord. Have you tried mixing them into your non-ActiveRecord model?

class MyModel
  include ActiveRecord::Validations

  # ...
end
Steve Madsen
Haven't tried that, very interesting... I kind of wanted to get the free initialize method and that as well, but with just validations I'll be happy...
Yar
+7  A: 

This is an approach I have used in the past:

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>>
John Topley
Beautiful. I'll be trying it out soon. Thanks!
Yar
+1  A: 

I found this link which works BEAUTIFULLY.

http://codetunes.com/2008/07/20/tableless-models-in-rails/

Yar
A: 

You may need to add this to the solution, proposed by John Topley in the previous comment:

class Tableless

  class << self
    def table_name
      self.name.tableize
    end
  end

end

class Foo < Tableless; end
Foo.table_name # will return "foos"

This provides you with a "fake" table name, if you need one. Without this method, Foo::table_name will evaluate to "tablelesses".

wireman
Interesting. I've been using this http://codetunes.com/2008/07/20/tableless-models-in-rails/ for some time without problems. Thanks.
Yar
Yes, that solution works and does need the table_name patch, because in that case the class inherits directly from `ActiveRecord::Base`.
wireman