0

im not able to display the validation error, even though it is validating the form. In my partial form

  • if @post.errors.any?

seems to be the problem, the @post returns a false for error and so no error is displayed. but the @comment returns a true for error, but im not able to replace @post with @comment since it throws an undefined 'comment' error..

my partial form which is begin called inside the show:

%html
%head
%title= @post.title
  %body
    %h2 Create Comments:
    = form_for([@post, @post.comments.build]) do |f|
      - if @post.errors.any?                # <--- Unsure what to do here..
        #error_explanation
        %h2
          = pluralize(@post.errors.count, "error")
          prohibited this cart from being saved:
        %ul
          - @post.errors.full_messages.each do |msg|
            %li= msg
    = f.label :Name
    %br
    = f.text_field :name 
    %br
    %br
    = f.label :Text
    %br
    = f.text_area :text
   %br
   %br
   = f.submit 

my comments controller:

def create
@post = Post.find(params[:post_id])

@comment = @post.comments.build(params[:comment])
   respond_to do |format| 
if @comment.save
    format.html { redirect_to @post }
else
    format.html { redirect_to @post }
end
   end
 end

this is show page from which im rendering the file:

%html
%head
  %title= @post.title
%body
  %strong Author name:
  = @post.author_name
  %br
  %br
  %strong Title:
  = @post.title
  %br
  %br
  %strong Email:
  = @post.email
  %br
  %br
  %strong Description:
  = @post.description

  %h2 Comments for this Post:

  = render :partial => @post.comments

  = render :partial => "comments/form"

2 Answers 2

1

You can use validates_associated on your post model to check for validation errors on your associated model.

Sign up to request clarification or add additional context in comments.

3 Comments

thanx for replying..the validation works fine but im not able to display the error inside the if condition the @post fails the if condition and comes out..
If you use the validates_associated, @post.errors will return errors for comments, and you can display them easily....
i did try it but it stil doesnt give me the error message..and when i debug the code i dont have the error message inside the @post..
0

You have to render new action if @comment.save fails

if @comment.save
    format.html { redirect_to @post }
else
    render :action => "new" 
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.