Verifying existance of related record

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?

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.

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