f.error_messages in Rails 3.0

前端 未结 6 1015
难免孤独
难免孤独 2020-11-29 00:04

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.

6条回答
  •  迷失自我
    2020-11-29 00:26

    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.

提交回复
热议问题