views:

353

answers:

2

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?

+2  A: 

http://blog.hasmanythrough.com/2007/7/14/validate-your-existence

class Post < ActiveRecord::Base
  belongs_to :category
  validates_existence_of :category 
end
Terry Lorber
Will this work if the category is scoped? Say that the category belongs to a Blog. The user should only be allowed to select categories belonging to to the blog.
Homar
@Homar Not sure about scoping, if the belongs_to association includes this restriction, I'd assume it would work.
Terry Lorber
+1  A: 

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.

Homar