【问题标题】:Rails: Empty comment on every new postRails:对每个新帖子都进行空评论
【发布时间】:2016-04-17 19:02:03
【问题描述】:

每当我在我的 Rails 博客应用程序上创建新帖子时,我都会从任何地方收到一条空评论。当我尝试删除该评论时,我收到一个错误No route matches [DELETE] "/posts/post_id/cmets"

这是_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 是辅助方法(如果动作名称是 edit 它将显示 Update post 并且如果它动作名称是 new 它将显示创建帖子)。

这是帖子的显示视图:

<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

这是创建新帖子时的样子:

这是_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)

【问题讨论】:

  • 你能发布你的控制器代码吗?
  • @jack 问题已更新。
  • 我没有看到任何可能导致此问题的原因。错误在别处。
  • 空白评论记录实际是什么时候创建的?它真的在您的PostsControllercreate 方法内吗?您的Post 模型中是否还有其他代码?当您尝试从 rails 控制台创建帖子时会发生什么?
  • 你能展示创建一个新帖子吗?

标签: ruby-on-rails


【解决方案1】:

在您的帖子显示视图中,您在渲染 cmets 之前渲染 cmets 表单。我认为在 cmets 表单 comments/_form.html.erb 中,您正在为帖子添加新评论,例如 @post.comments.new

一种解决方法是仅使用 &lt;%= render @post.comments.select(&amp;:persisted?) %&gt; 呈现持久化 cmets。

【讨论】:

  • 是的,同意这个猜测。如果由于form_for 而在内存中出现了新的Comment,那就是罪魁祸首。
  • @Kev,非常感谢,@post.comments.select(&amp;:persisted?) 工作!我检查了我的所有观点,但我仍然不太确定是什么导致了错误。也许我很快就会知道。
猜你喜欢
  • 1970-01-01
  • 2013-04-12
  • 1970-01-01
  • 2023-04-10
  • 2021-10-05
  • 1970-01-01
  • 2021-07-13
  • 2015-10-11
  • 2014-06-11
相关资源
最近更新 更多