The Blog

Validate presence of at least one associated record

I’ve previously had the need to validate, that at least on record in a has_many association existed. For that I used a custom validator. But today i realized that the presence validator in rails 3 will do exactly that:

class Parent < ActiveRecord::Base
  has_many :children
  validates :children, :presence => true

If you need a custom message, that’s built into the new validation syntax for rails 3:

  validates :children, :presence =>
    { :message => 'there should be at least one child' }

Simply wanted to share this, just in case it could save someone the hassle of building a custom validator.


Got something to say? Feel free, I want to hear from you! Leave a Comment

  1. usatosi says:

    great tip! thanks!

  2. ravionrails says:

    Thanks Jeppe

Leave a Comment

Let us know your thoughts on this post but remember to place nicely folks!