Alex Rivera | Logout

Rails: Validating existence of an association

Asked 2009-08-26T03:33:00.300
18

I have a Category and a Post model, with each Post belonging to a Category. Before creating or updating a post, I need to check that the category selected exists. What's the best way to validate this information?

At the moment, I'm doing a find in the controller to ensure that the category exists. Is it possible to put these kinds of validations in the model?

Edit
Report

2 Answers

20

In Rails 3.2, validates_existence_of is replaced by validates_presence_of.

answered 2012-06-16T09:35:35.683
4

I've put this in my model:

  validate :ensure_category_exists

  def ensure_category_exists
    errors.add('Category') unless self.blog.categories.find_by_id(self.category_id)
  end

Which prints "Category is invalid" if the category does not exist for the parent blog.

answered 2009-08-26T06:22:59.723

Your Answer