Validate fields and display errors from two models?


I have here a problem I’ve been working at for a little while but I
can’t seem to get the error messages to appear correctly.

My form looks something like this for “ModelA”:

[errors_for “modelA”]
[form for “modelA”]
[text “modelA” “fieldname1”]
[text “modelB” “fieldname2”]

The reason for this is I can create many modelB’s for each modelA but
when I create modelA I want it to create the first modelB with it.


In my Model:

class ModelA
validates_presence_of :fieldname1
has_many :modelBs
validates_associated :modelB

class ModelB
validates_presence_of :fieldname2
belongs_to :modelA

I’ve tried creating several custom error handlers to support this but
none of them have worked for me yet.

Are there any resources from people who have already done this? Thanks
I’ve been looking everywhere and I must be doing something wrong.

Just to be specific I want to see a usable model.errors hash when
validates_associated is called so that I can make a error handler
sufficient enough to show the errors for all fields.

model.errors.inspect gives me this:

#<ActiveRecord::Errors:0xb759046c @errors={“title”=>[“can’t be blank”],
“comments”=>[“is invalid”, “is invalid”]},
@base=#<Cerebration:0xb7597640 @errors=#<ActiveRecord::Errors:0xb759046c
…>, @new_record=true, @folder=#<Folder:0xb757ebb8
@attributes={“discussable_id”=>“65”, “cerebrations_count”=>“8”,
“title”=>“News item title Folder”, “discussable_type”=>“News”,
“id”=>“1”}>, @comments=[#<Comment:0xb75943c8
@errors=#<ActiveRecord::Errors:0xb758fef4 @errors={“content”=>[“can’t be
blank”]}, @base=#<Comment:0xb75943c8 …>>, @new_record=true,
@attributes={“updated_on”=>nil, “cerebration_id”=>0, “content”=>"",
“user_id”=>0, “created_at”=>nil}>], @attributes={“title”=>"",
“icon”=>“none”, “folder_id”=>“1”, “comments_count”=>0}>

I have no idea how to work with this. Given my models the errors I
should be returned here are “Title can’t be blank” and “Content can’t be
blank”. Content is in the associated model, called with
validates_associated :comments

Please help.