Validation Non Activerecord Objects

Hi,

I know there are ways to validation non active record objects from the
link below.

http://wiki.rubyonrails.com/rails/pages/HowToUseValidationsWithoutExtendingActiveRecord

In activerecord validations when a field fails validation it is
highlighted in red and the name of the field appears in the error log at
the top of the page. Is it possible to use this functionality with non
active record objects or do you have to write your own?

Any suggestions appreciated?

I think you can declare a validate method in your model and use
errors.addto add messages for your view. Not exactly sure though.

-m

@John:

See this little writeup I did a while back… uses an example from Rick
Olson’s blog and expands upon it. This should give you exactly what you
need.

def method_missing(symbol, @params)

Shouldn’t @params be *params ?

There is a chapter in the Rails Recipes book on this. Create a
validateable.rb file and add:

module Validateable
[:save, :save!, :update_attribute].each{|attr| define_method(attr){}}
def method_missing(symbol, @params)
if(symbol.to_s =~ /(.*)_before_type_cast$/)
send($1)
end
end
def self.append_features(base)
super
base.send(:include, ActiveRecord::Validations)
end
end

then in your model:

class Person
include Validateable
attr_accessor :age
validates_numericality_of :age
end

you can take advantage of the valid?() method now, and also use
error_messages_on() and error_messages_for() helpers

I’m using this and it works well, and is nicely encapsulated.

http://www.agilewebdevelopment.com/plugins/active_form

Wes

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs