Error messages for nested resource; guide says to use f.error_messages, but is deprecated/didn't wor

I’ve been trying to set up a new Rails 3 project as per, but I’m running
into difficulty with displaying errors when adding a new comment. The
comments are a nested resource of posts. On the posts/show page, I

<%= form_for([@post,]) do |f| %>
<%= f.error_messages %>

<%= f.label :commenter %>
<%= f.text_field :commenter %>
<%= f.label :body %>
<%= f.text_area :body %>
<%= f.submit %>
<% end %>

But the f.error_messages is deprecated. I’ve read online that one
solution is to use a partial and pass in the offending object as a
target to it, but I don’t know how to reference the comments object.
It would look something like

<%= form_for([@post,]) do |f| %>
<%= render"shared/error_messages", :target => @comment %>

<% end %>

where @comment is the comment object. The examples online don’t show
how to do it when you pass an array to form_for. How can I get the
error messages to show up for new comments?

For reference, the CommentsController looks like:

class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)

and the Comment model looks like:

class Comment < ActiveRecord::Base
validates :commenter, :presence => true
validates :body, :presence => true
belongs_to :post

You want to set your comment variable in the controller:

def new
@comment =

so your form is

<%= form_for([@post, @comment]) do |f| %>
<%= render"shared/error_messages", :target => @comment %>
<% end %>

If you build the comment in the form (which you shouldn’t be doing
anyways if you’re sticking to MVC principles), then when you render the
form, a new comment object is always created. Since it’s a new object,
it won’t have any errors.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs