Forum: Ruby on Rails has_many validation the Rails way

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
TomRossi7 (Guest)
on 2008-10-09 22:51
(Received via mailing list)
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

class Post < ActiveRecord::Base
  belongs_to :blog
  validates_presence_of  :name
  validates_presence_of  :blog_id

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.

Roy P. (Guest)
on 2008-10-09 23:23
(Received via mailing list)
Is this the multiple-models-one-form problem?  If so, see this & the
prior 2 railscasts:

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...


TomRossi7 (Guest)
on 2008-10-09 23:39
(Received via mailing list)

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?

This topic is locked and can not be replied to.