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
so I added the following code to my Post-view:
= form_for([@post, @post.comments.build]) do |f|
= f.label :author
= f.text_field :author
= f.label :content
= f.text_area :content
= f.submit
I added some validation to my Comments-model, so it looks like:
class Comment < ActiveRecord::Base
belongs_to :post
validates_presence_of :author
end
My comments-controller looks like:
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to @post
end
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
- if @comment.errors.any?
- @comment.errors.full_messages.each do |error|
= 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