Rails:每个新帖子都有空评论

时间:2016-04-17 19:02:03

标签: ruby-on-rails

每当我在我的Rails博客应用程序上创建新帖子时,我都会收到一条空的评论。当我尝试删除该评论时,我收到错误没有路线匹配[删除]“/ posts / post_id / comments”

这是 _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 是帮助方法(如果操作名称为编辑,则会显示更新帖子,如果操作名称为 new < / em>它将显示创建帖子)。

这是帖子的展示视图:

<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)

1 个答案:

答案 0 :(得分:2)

在帖子展示视图中,您可以在呈现评论之前呈现评论表单。我在评论表单comments/_form.html.erb中估算,您正在使用类似@post.comments.new的内容向帖子添加新评论。

一种解决方法是仅使用<%= render @post.comments.select(&:persisted?) %>呈现持久性评论。