2016-04-17 5 views
0

Всякий раз, когда я создаю новое сообщение в своем блоге в блоге Rails, я получаю пустой комментарий из ниоткуда. Когда я пытаюсь удалить этот комментарий, я получаю сообщение об ошибке Нет совпадения маршрутов [DELETE] "/ posts/post_id/comments".Rails: Пустой комментарий к каждому новому сообщению

Это _form.html.erb (для создания и редактирования сообщений):

<% if @post.errors.any? %> 
    <div class="alert alert-danger"> 
     <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> 
     Fix the errors before creating an article! 
    </div> 
    <div id="error_explanation"> 
     <h2> 
      <%= pluralize(@post.errors.count, "error") %> prohibited 
      this article from being saved: 
     </h2> 
     <ul> 
      <% @post.errors.full_messages.each do |msg| %> 
       <li><%= msg %></li> 
      <% end %> 
     </ul> 
    </div> 
<% end %> 

<%= form_for @post do |f| %> 
    <%= f.label :title %><br/> 
    <%= f.text_field :title %><br/> 

    <%= f.label :body %><br/> 
    <%= f.text_area :body %><br/> 

    <%= f.submit submit_button_text, :class => "btn btn-default" %> 
<% end %> 

SUBMIT_BUTTON_TEXT является вспомогательным метод (если имя действия редактировать он будет показывать Обновление поста и если это имя действия оно покажет Создать пост).

Это шоу вид для сообщений:

<h1 class="post_title"><%= @post.title %></h1> 
<div class="post_body"><%= @post.body %></div> 

<div> 
    <%= link_to "Edit post", edit_post_path, :class => "btn btn-warning" %> 
    <%= link_to "Delete", post_path(@post), 
         method: :delete, 
         data: { confirm: "Are you sure?" }, 
         :class => "btn btn-danger" 
    %> 
</div> 

<h3 class="add_comment_title">Add a comment</h3> 
<%= render 'comments/form' %> 

<h3 class="comments_title">Comments</h3> 
<div class="list-group comments_section"> 
    <%= render @post.comments %> 
</div> 

комментарий модель:

class Comment < ActiveRecord::Base 
    belongs_to :post 
    validates :author, presence: true, 
        length: { minimum: 3, maximum: 10 } 
    validates :body, presence: true, 
        length: { minimum: 30, maximum: 400} 
end 

Сообщение Модель:

class Post < ActiveRecord::Base 
    has_many :comments, -> { order(created_at: :desc) }, dependent: :destroy 
    validates :title, presence: true, 
        length: { minimum: 5, maximum: 50 } 
    validates :body, presence: true, 
        length: { minimum: 20, maximum: 1000 } 
end 

Сообщений контроллер:

class PostsController < ApplicationController 
    before_action :find_post, only: [:show, :edit, :update, :destroy] 

    def index 
     @posts = Post.all.order("created_at DESC") 
    end 

    def new 
     @post = Post.new 
    end 

    def create 
     @post = Post.new(post_params) 

     if @post.save 
      redirect_to @post 
     else 
      render 'new' 
     end 
    end 

    def show 
    end 

    def edit 
    end 

    def update 

     if @post.update(post_params) 
      redirect_to @post 
     else 
      render 'edit' 
     end 

    end 

    def destroy 
     @post.destroy 
     redirect_to posts_path 
    end 

    private 

    def post_params 
     params.require(:post).permit(:title, :body) 
    end 

    def find_post 
     @post = Post.find(params[:id]) 
    end 
end 

Комментарии контроллер:

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

    def destroy 
     @post = Post.find(params[:post_id]) 
     @comment = @post.comments.find(params[:id]) 
     @comment.destroy 
     redirect_to post_path(@post) 
    end 

    private 

    def comment_params 
     params.require(:comment).permit(:author, :body) 
    end 
end 

И вот как это выглядит, когда новый пост создан:

enter image description here

Вот _comment.html.erb:

<div class="list-group-item comment"> 
    <h4 class="list-group-item-heading"> 
     <%= comment.author %> 
    </h4> 

    <p class="list-group-item-text"> 
     <%= comment.body %> 
    </p> 

    <p> 
     <%= link_to "Delete comment", [comment.post, comment], 
            method: :delete, 
            data: { confirm: "Are you sure?" } 
     %> 
    </p> 
</div> 

Вот что я получил в консоли, когда я сделал новое сообщение:

Started POST "/posts" for 127.0.0.1 at 2016-04-18 18:37:42 +0200 
Processing by PostsController#create as HTML 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"q5sYwu5AB0whgwz/0VFOVh9nzq89VBUO2mGzhK7Aw0W4iL/JLsJn2aNH4aCO9r2gTsLjzDQUt5nwGOdecNnVDA==", "post"=>{"title"=>"New post #5", "body"=>"Some text for new post."}, "commit"=>"Create post"} 
    (0.4ms) begin transaction 
    SQL (1.2ms) INSERT INTO "posts" ("title", "body", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["title", "New post #5"], ["body", "Some text for new post."], ["created_at", "2016-04-18 16:37:42.811714"], ["updated_at", "2016-04-18 16:37:42.811714"]] 
    (161.2ms) commit transaction 
Redirected to http://localhost:3000/posts/15 
Completed 302 Found in 180ms (ActiveRecord: 162.8ms) 


Started GET "/posts/15" for 127.0.0.1 at 2016-04-18 18:37:43 +0200 
Processing by PostsController#show as HTML 
    Parameters: {"id"=>"15"} 
    Post Load (0.7ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1 [["id", 15]] 
    Rendered comments/_form.html.erb (60.7ms) 
    Comment Load (0.7ms) SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = ? ORDER BY "comments"."created_at" DESC [["post_id", 15]] 
    Post Load (0.4ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1 [["id", 15]] 
    Rendered comments/_comment.html.erb (36.7ms) 
    Rendered posts/show.html.erb within layouts/application (130.4ms) 
Completed 200 OK in 463ms (Views: 395.7ms | ActiveRecord: 2.4ms) 
+0

Можете ли вы опубликовать свой код контроллера? – jack

+0

@jack Вопрос обновлен. – Nikola

+0

Я не вижу ничего, что могло бы вызвать это. Ошибка в другом месте. –

ответ

2

В представлении «Просмотр сообщений» вы представляете форму комментариев перед тем, как делать комментарии. Я вхожу в форму комментариев comments/_form.html.erb вы добавляете новый комментарий к сообщению с чем-то вроде @post.comments.new.

Одним из способов решения проблемы является только сохранение сохраненных комментариев с помощью <%= render @post.comments.select(&:persisted?) %>.

+0

Да, согласитесь с этим догадкой. Если у вас есть новый 'Комментарий' в памяти из-за вашей' form_for', это преступник. –

+0

@Kev, спасибо большое, '@ post.comments.select (&: persisted?)' Работал! Я проверил все свои взгляды, и я все еще не совсем уверен, что вызвало ошибку. Может быть, я скоро узнаю. – Nikola

Смежные вопросы