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.
On Mar 16, 2006, at 1:47 PM, Richard Williams wrote:
>
> 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?
>
>
>
> --
> Posted with http://DevLists.com. Sign up and save your time!
> _______________________________________________
> Rails mailing list
> Rails@lists.rubyonrails.org
> http://lists.rubyonrails.org/mailman/listinfo/rails