# About custom validations

**URL:** <https://www.ruby-forum.com/t/about-custom-validations/177168>\
**Category:** Rails\
**Created:** [October 12, 2009, 7:46pm UTC](https://www.ruby-forum.com/t/about-custom-validations/177168 "2009-10-12T19:46:03Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bakkhoz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/d6d6ee/32.png) [@bakkhoz](https://www.ruby-forum.com/u/bakkhoz)\
**Post date:** [October 12, 2009, 7:46pm UTC](https://www.ruby-forum.com/t/about-custom-validations/177168/1 "2009-10-12T19:46:03Z")

</div>

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:

```auto
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.

---

<div class="post-metadata">

**Author:** ![bakkhoz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/d6d6ee/32.png) [@bakkhoz](https://www.ruby-forum.com/u/bakkhoz)\
**Post date:** [October 12, 2009, 11:17pm UTC](https://www.ruby-forum.com/t/about-custom-validations/177168/2 "2009-10-12T23:17:03Z")

</div>

On Mon, Oct 12, 2009 at 2:46 PM, Sergio Aristizabal  
[removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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 ~
