About custom validations

Hello,

I suppose this topic has been widely discussed, but i’ve not found
exactly what i need.

I thought validate_associations would in fact validate the associations
of my models, but it simply verifies that the fields of the object are
valid. So i need to create some custom validations to do

I found one solution:

validate :obj_must_exist

def obj_must_exist
  errors.add(:obj_id, "must point to an existing obj") if obj_id &&
obj.nil?
end

But now i need it in a helper or something like that, because i’ve to
reuse the same validation several times. I created a file in
config/initializers called validations.rb and put this:

ActiveRecord::Base.class_eval do
def self.validates_object_exists(obj, obj_id)
obj.errors.add(obj_id, “must point to an existing #{obj}”) if obj_id
|| obj.nil?
end
end

But it’s just not working… So, what’s the “rails way” to do that?

Thank you.

On Mon, Oct 12, 2009 at 2:46 PM, Sergio Aristizabal
[email protected] wrote:

I found one solution:
But now i need it in a helper or something like that, because i’ve to
But it’s just not working… So, what’s the “rails way” to do that?
What is “just not working”?
What is exactly the given error?
Are you sure the file is getting loaded?
Have you tried explicitly loading it?


Leonardo M…
There’s no place like ~

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