Forum: Ruby on Rails Verifying existance of related record

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
5d15c6821f3c3054c04b85471824ba7c?d=identicon&s=25 Richard Williams (Guest)
on 2006-03-16 22:49
(Received via mailing list)
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?
24d3102d656a4654db23d28382a2d6f0?d=identicon&s=25 Timothy Bennett (Guest)
on 2006-03-16 23:01
(Received via mailing list)
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.
5d15c6821f3c3054c04b85471824ba7c?d=identicon&s=25 Richard Williams (Guest)
on 2006-03-16 23:38
(Received via mailing list)
Thanks.  I figured I was overcomplicating this.  That worked perfectly.
This topic is locked and can not be replied to.