Rails 3.0 deprecated f.error_messages
and now requires a plugin to work correctly - I however want to learn how to display error messages the (new) native way.
I guess that the [@post, @post.comments.build]
array is just passed to polymorphic_path
inside form_for
. This generates a sub-resource path for comments (like /posts/1/comments
in this case). So it looks like your first example uses comments as sub-resources to posts, right?.
So actually the controller that will be called here is the CommentsController
. The reason why Lukas' solution doesn't work for you might be that you actually don't use @post.comments.build inside the controller when creating the comment (it doesn't matter that you use it in the view when calling form_for
). The CommentsController#create
method should look like this (more or less):
def create
@post = Post.find(params[:post_id]
@comment = @post.comments.build(params[:comment])
if(@comment.save)
# you would probably redirect to @post
else
# you would probably render post#show or wherever you have the form
end
end
Then you can use the code generated by scaffolding, only replace @post
instance variable with @comment
in all the lines except form_for
call.
I think it may also be a good idea to add the @comment = @post.comment.build
to the controller method that displays this form and use form_for([@post, @comment], ...)
to keep the form contents displayed in the form if there're errors.
If this doesn't work and you're not able to figure it out, please add your CommentsController#create
method to the question.