# Validation errors from associated models

**URL:** <https://discuss.rubyonrails.org/t/validation-errors-from-associated-models/60394>\
**Category:** rubyonrails-talk\
**Created:** [August 14, 2011, 11:08pm UTC](https://discuss.rubyonrails.org/t/validation-errors-from-associated-models/60394 "2011-08-14T23:08:24Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Dennis\_Schubert](https://avatars.discourse-cdn.com/v4/letter/d/7cd45c/32.png) [@Dennis\_Schubert](https://discuss.rubyonrails.org/u/Dennis_Schubert)\
**Post date:** [August 14, 2011, 11:08pm UTC](https://discuss.rubyonrails.org/t/validation-errors-from-associated-models/60394/1 "2011-08-14T23:08:24Z")

</div>

Hey guys,

I have a weird problem and I think you are able to solve it easy.

I have two models - "Posts" and "Comments". A post :has\_many comments and a comment :belongs\_to a post. I followed the guide on

> **[Getting Started with Rails — Ruby on Rails Guides](https://guides.rubyonrails.org/getting_started.html#adding-a-second-model)**
>
> Getting Started with RailsThis guide covers getting up and running with Ruby on Rails.After reading this guide, you will know: How to install Rails, create a new Rails application, and connect your application to a database. The general layout of a...

so I added the following code to my Post-view:

&nbsp;&nbsp;&nbsp;&nbsp;= form\_for([@post, @post.comments.build]) do |f| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;= f.label :author &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;= f.text\_field :author &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;= f.label :content &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;= f.text\_area :content &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;= f.submit

I added some validation to my Comments-model, so it looks like:

&nbsp;&nbsp;&nbsp;&nbsp;class Comment \< ActiveRecord::Base &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;belongs\_to :post &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;validates\_presence\_of :author &nbsp;&nbsp;&nbsp;&nbsp;end

My comments-controller looks like:

&nbsp;&nbsp;&nbsp;&nbsp;class CommentsController \< ApplicationController &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;def create &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@post = Post.find(params[:post\_id]) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@comment = @post.comments.create(params[:comment]) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;redirect\_to @post &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end &nbsp;&nbsp;&nbsp;&nbsp;end

Creating new comments works fine, and if I leave "author" empty the comment will not be saved. That's good. But now I wanna show the validation-errors. Normally I would do that with adding something like

&nbsp;&nbsp;&nbsp;&nbsp;- if @comment.errors.any? &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- @comment.errors.full\_messages.each do |error| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;= error

to the formular in the post-view, but of course @comment is undefine in that view.

How can I show the errors there?

Regards, Dennis
