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”
unless Category.find(:first, :conditions => “categoryid =
errors.add(:categoryid, “is not a valid category id”)
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?