# Has\_many validation the Rails way

**URL:** <https://www.ruby-forum.com/t/has-many-validation-the-rails-way/150555>\
**Category:** Rails\
**Created:** [October 9, 2008, 8:51pm UTC](https://www.ruby-forum.com/t/has-many-validation-the-rails-way/150555 "2008-10-09T20:51:26Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [October 9, 2008, 8:51pm UTC](https://www.ruby-forum.com/t/has-many-validation-the-rails-way/150555/1 "2008-10-09T20:51:26Z")

</div>

Okay, this is something I run into a lot and don’t really have a great  
solution. Here is a simple example:

class Blog \< ActiveRecord::Base  
has\_many :posts  
validates\_presence\_of :name  
end

class Post \< ActiveRecord::Base  
belongs\_to :blog  
validates\_presence\_of :name  
validates\_presence\_of :blog\_id  
end

Now, if I want to create a blog and post at the same time I don’t want  
either to be created if one of them fails. So imagine that I have a  
new valid blog, but a post with no name. I do not want the blog to be  
created because the post failed validation.

Thanks,  
Tom

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [October 9, 2008, 9:23pm UTC](https://www.ruby-forum.com/t/has-many-validation-the-rails-way/150555/2 "2008-10-09T21:23:09Z")

</div>

Is this the multiple-models-one-form problem? If so, see this & the  
prior 2 railscasts:

> **[\#75 Complex Forms Part 3 - RailsCasts](http://railscasts.com/episodes/75-complex-forms-part-3)**
>
> Short Ruby on Rails screencasts containing tips, tricks and tutorials. Great for both novice and experienced web developers.

The problem that’s not treated in those (IIRC) is how to give  
informative error messages when child item validation fails. IIRC, you  
get _something_ but it’s not super informative…

HTH,

-Roy

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [October 9, 2008, 9:39pm UTC](https://www.ruby-forum.com/t/has-many-validation-the-rails-way/150555/3 "2008-10-09T21:39:37Z")

</div>

Roy,

I have probably 3 different solutions I’ve used in different places,  
but they each have different drawbacks. The closest solution is the  
one you refer to, where when the child validates it has an error on  
the required parent\_id, but the parent\_id is only missing because the  
child failed validation!

Any beautiful solutions out there?

Thanks,  
Tom
