Re: Validations for non-ActiveRecord Model Objects

Rick Olson
Fri, 02 Dec 2005 16:38:31 -0000

On 12/2/05, Peter Donald
<peter.j.donald-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
wrote:
> Hi,
>
> I just worked on getting validations for non-ActiveRecord model
> objects working. I essentially implemented an ActiveForm object that
> you can subclass for your own non-database form objects. The file is
> available from my blog [1] and I wouldn''t mind some feedback on
> whether my assumptions are right. It seems to work for me and makes it
> much easier to write non-database bound forms.
>
> [1]
http://www.realityforge.org/articles/2005/12/02/validations-for-non-activerecord-model-objects
>
> --
> Cheers,
>
> Peter Donald

Here''s my approach to the problem.  Instead of making my own class and
reimplementing the validations, I just removed the code that grabs the
table info:

class Contact < 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

  column :name,          :string
  column :city,          :string
  column :state,         :string
  column :phone,         :string
  column :email_address, :string

  validates_presence_of :name, :email_address
end

It''s still technically a model, so you can call #save on it.  But just
calling valid? works fine.

http://rails.techno-weenie.net/tip/2005/11/19/validate_your_forms_with_a_table_less_model


--
rick