Saturday, August 4, 2012

[Rails] ActiveRecord::Validator vs ActiveModel::Validator

I know that there is an ActiveModel Validator class

https://github.com/rails/rails/blob/master/activemodel/lib/active_model/validator.rb

which is used for the class level validation macros.

But I didn't find a an ActiveRecord Validator class.

From my understanding in Rails 3, validations have been moved into
ActiveModel to leave ActiveRecord as an ORM.

So now I see this Rails 3 code in a Rails 3 book and get confused:

Class EmailValidator < ActiveRecord::Validator
def validate()
email_field = options[:attr]
record.errors[email_field] << "is not valid" unless
record.send(email_field) =~ /^[a-z]$/
end
end

class Account < ActiveRecord::Base
validates_with EmailValidator, :attr => :email
end

Where is this ActiveRecord::Validator coming from? Also why does it
exist when you can simply do this in ActiveModel:

class RandomlyValidator < ActiveModel::Validator
def validate(record)
record.errors[:base] << "FAIL #1" unless first_hurdle(record) #add
error messages to the whole object instead of a particular attribute
using the :base key.
record.errors[:base] << "Fail #2" unless second_hurdle(record)
record.errors[:base] << "Fail #3" unless third_hurdle(record)
end

private

def first_hurdle(record)
rand > 0.3
end

def second_hurdle(record)
rand > 0.6
end

def third_hurdle(record)
rand > 0.9
end
end

class Report < ActiveRecord::Base
validates_with RandomlyValidator
end

thanks for response

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate