# Verifying existance of related record

**URL:** <https://www.ruby-forum.com/t/verifying-existance-of-related-record/55093>\
**Category:** Rails\
**Created:** [March 16, 2006, 10:49pm UTC](https://www.ruby-forum.com/t/verifying-existance-of-related-record/55093 "2006-03-16T22:49:33Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![rrwhite](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e19adc/32.png) [@rrwhite](https://www.ruby-forum.com/u/rrwhite)\
**Post date:** [March 16, 2006, 10:49pm UTC](https://www.ruby-forum.com/t/verifying-existance-of-related-record/55093/1 "2006-03-16T22:49:33Z")

</div>

Is there an easy way to validate that a related record exists?

I’ve got a table that contains a set of categories and I want to make  
sure the user has entered a vaild category (i.e. a category that exists  
in the categories table). So in the model of the table I put this:

class Master \< ActiveRecord::Base  
belongs\_to :category, :foreign\_key =\> “categoryid”

validates\_presence\_of :categoryid

def validate\_on\_create  
unless Category.find(:first, :conditions =\> “categoryid =  
#{categoryid}”)  
errors.add(:categoryid, “is not a valid category id”)  
end  
end  
end

However this does not work because the “validate\_on\_create” is being run  
before the “validates\_presence\_of”, so if the categoryid is nil the  
category.find throws an SQL syntax exception.

I would have thought that the belongs\_to would check for the existance  
of the related row. No?

---

<div class="post-metadata">

**Author:** ![rrwhite](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e19adc/32.png) [@rrwhite](https://www.ruby-forum.com/u/rrwhite)\
**Post date:** [March 16, 2006, 11:01pm UTC](https://www.ruby-forum.com/t/verifying-existance-of-related-record/55093/2 "2006-03-16T23:01:43Z")

</div>

All you need is:

class Master \< ActiveRecord::Base  
belongs\_to :category, :foreign\_key =\> “categoryid”

validates\_presence\_of :category, :message =\> “is not a valid  
category”  
end

or something like that.

---

<div class="post-metadata">

**Author:** ![rrwhite](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e19adc/32.png) [@rrwhite](https://www.ruby-forum.com/u/rrwhite)\
**Post date:** [March 16, 2006, 11:38pm UTC](https://www.ruby-forum.com/t/verifying-existance-of-related-record/55093/3 "2006-03-16T23:38:31Z")

</div>

Thanks. I figured I was overcomplicating this. That worked perfectly.
