ruby on rails - Trying to show error messages, but running into: undefined method `errors' for nil:NilClass -


i trying implement error messages in rails , somehow fail work @ 1 point.

the view trying add error messages:

<%= form_for([@post, @post.comments.build], html: {class: 'form-horizontal'}) |f| %>              <% if @comment.errors.any? %>                  <div id="errorexplanation" class="span5 offset1 alert alert-error">                     <button type="button" class="close" data-dismiss="alert">&times;</button>                      <h4>something went wrong!</h4><br>                      <% @post.errors.full_messages.each |msg| %>                     <p><%= msg %></p>                     <% end %>                 </div>          <% end %> 

and controller:

def create @post = post.find(params[:post_id]) @comment = @post.comments.create(params[:comment].permit(:commenter, :body)) redirect_to post_path(@post) end 

and error message:

undefined method `errors' nil:nilclass extracted source (around line #65):

<li>             <%= form_for([@post, @post.comments.build], html: {class: 'form-horizontal'}) |f| %>  65 ->                       <% if @comment.errors.any? %>                      <div id="errorexplanation" class="span5 offset1 alert alert-error">                         <button type="button" class="close" data-dismiss="alert">&times;</button> 

the comments of course belong post can have many comments. help? tried think of (which not since new ror ;) - including various ways of trying error messages (@post.comment.errors.any? etc.).

thanks in advance. timo

from comments there many things going on here.

you're trying create comment, form action should commentscontroller#create. view makes sense postscontroller#show (you don't specify), , before rendering need instantiate @comment. possibly:

postscontroller

def show   @post = post.find(params[:id])   @comment = @post.comments.build end 

commentscontroller

def create   @post = post.find(params[:post_id])   @comment = @post.comments.build(params[:comment].permit(:commenter, :body))   if @comment.save     redirect_to post_path(@post)   else     render :file => "posts/show"   end  end 

note must render , not redirect keep hold of @comment instance , can render errors.

posts/show.html.erb

<%= form_for([@post, @post.comments.build], html: {class: 'form-horizontal'}) |f| %>     <% if @comment.errors.any? %> 

whether correct depend on routes.rb. i'm assuming comments nested resource in posts, question leads think.


Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -