Forum: Ruby on Rails Validate fields and display errors from two models?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
110c7df9fbc932cfe55c6317aedd04b3?d=identicon&s=25 Nathan (Guest)
on 2006-03-10 02:37
Hi,

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"]
[submit]
[/form]

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.

So...

In my Model:

class ModelA
validates_presence_of :fieldname1
has_many :modelBs
validates_associated :modelB
end

class ModelB
validates_presence_of :fieldname2
belongs_to :modelA
end

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.
7fb3901cce24ff7f9bd517ea92c898ae?d=identicon&s=25 Nathan Ventura (pie-social)
on 2006-03-11 02:13
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.
This topic is locked and can not be replied to.