Validating comments with error messages

If you’ve watched the “15 minutes blog” screencast and like me couldn’t get comment validation error messages to display, here’s the solution.This is the code I used to create comments


def comment
  Post.find(params[:id]).comments.create(params[:comment])
  flash[:notice] = 'Comment successfully added'
  redirect_to :action => 'show', :id => params[:id]
end

Unfortuantely when the comment fails validation it comes back with the message ‘Comment successfully added’ when in fact it hasn’t been. After looking around for a solution I finally found out what’s happening and how to fix it.

Validation errors are only available in the action where they’re made, so when we redirect to the ’show’ action we lose the error message. To solve this we need to figure out if the comment was successfully created, if it was, redirect to the ’show’ action, else, render the same page again.

Here’s how we do that


def create_comment
  @post = Post.find(params[:id])
  @comment = Comment.new(params[:comment])
  @comment.post_id = @post.id
  if @comment.save
    flash[:notice] = 'Comment successfully added'
    redirect_to :action => 'show', :id => @post.id
  else
    render :action => 'show'
  end
end

Posted on Wednesday, March 19th, 2008 by David

Leave a Reply