新手问题 评论列表为什么会多出一个评论按钮来啊?文章列表也是这样写的都没有问题啊?

hemengzhi88 · 2015年12月18日 · 最后由 alicebobby 回复于 2024年03月13日 · 2111 次阅读

首先感谢抽空来帮我这个新手找问题的朋友!

代码是这个样子的


<% @article.comments.each do |f| %>
    <div class="col-md-12"> 
        <h4> <%= f.email %> </h4>
        <div>
        <h5> <%= f.content %> </h5>
            <% if signed_in? %>
            <%= link_to "删除该评论", f , method: :delete , class: "btn-sm btn-primary" %>
            <% end %>
        </div>
    </div>
<% end %>

效果让我一头雾水!

数据库是这样的,属于这篇文章的评论数是 2,字段 article_id:8

2.2.1 :003 > Comment.all
  Comment Load (0.8ms)  SELECT "comments".* FROM "comments"  ORDER BY created_at
 => #<ActiveRecord::Relation [#<Comment id: 6, email: "[email protected]", content: "fdsaf ", article_id: 4, created_at: "2015-12-18 06:38:36", updated_at: "2015-12-18 06:38:36">, #<Comment id: 7, email: "[email protected]", content: "加入我们,现在刚刚好!直接给我私信.", article_id: 8, created_at: "2015-12-18 07:58:01", updated_at: "2015-12-18 07:58:01">, #<Comment id: 8, email: "[email protected]", content: "加入我们,现在刚刚好!直接给我私信.",article_id: 8, created_at: "2015-12-18 08:00:14", updated_at: "2015-12-18 08:00:14">]> 
2.2.1 :004 > Comment.count
   (0.1ms)  SELECT COUNT(*) FROM "comments"
 => 3 

我猜是有一条空数据?

#1 楼 @cqcn1991 看了你的回答,我把数据库对应内容也贴上来了。

你是不是为下面的 comment form new 了一个 comment

类似 @article.comments.new

然后 @article.comments 会有一个空的 comment

#3 楼 @kikyous 一语中的! @kikyous 谢谢提示,让我自己不知道找到什么时候去了。 开始我的 article_controller.rb 是这样写的。

class ArticlesController < ApplicationController    
    def show
        @article = Article.find(params[:id])
        @comment =@article .comments.build
    end
end 

而 comment_controller.rb 是这样的

class CommentsController < ApplicationController
    def create
        @comment = Comment.create(comment_params)
    end
end

后面把 article 中@comment=@article.comments.build 换成@comment=Comment.create 就 OK 了。

#4 楼 @hemengzhi88 兄弟这样不行啊 @comment=Comment.create 会新建一条空数据并且保存到数据库里面

#5 楼 @kikyous 兄弟,我印象中:

new :只是在内存中新建一个对象,操作数据库要调用save方法。
create = new + save。
build:与new基本相同,多用于一对多情况下。

如果加上数据验证,空数据的 create 应该不会成功吧。

#5 楼 @kikyous 我试过了,我的不会在数据库新建空数据,但是我这样写感觉怪怪的,我想用 build 但是这样我感觉就要把 current_article 写到 session 里面了,我这样写在 form 里面加了一个<%= f.text_field :article_id,type:"hidden" ,value:@article.id%>来传文章的 id,你有没有更好的解决办法?

#7 楼 @hemengzhi88

Comment.new(article: @article)

#8 楼 @kikyous 谢谢,我试试!

阅读您的回复后,我已经提供了数据库的匹配内容。 retro bowl

需要 登录 后方可回复, 如果你还没有账号请 注册新账号