【问题标题】:Rails shows non existent database recordsRails 显示不存在的数据库记录
【发布时间】:2015-04-19 18:11:29
【问题描述】:

Rails 显示 Comment 模型的实例存在,即使数据库为空。我显示Comment 的代码是

<% @post.comments.each do |c| %>
   <%= c %>
<% end %>

然后,我得到#&lt;Comment:0x007fe971c02800&gt;,如果我这样做c.attributes,我得到 {"id"=&gt;nil, "body"=&gt;nil, "author"=&gt;nil, "post_id"=&gt;37, "deleted"=&gt;nil, "locked"=&gt;nil, "created_at"=&gt;nil, "updated_at"=&gt;nil},但该表没有记录。如果我将该代码更改为

<% @post.comments.each do |c| %>
   <%= c.body %>
<% end %>

我什么也得不到。 使用closure_tree 可能对我有帮助。 如果有帮助,这里是表的架构:

create_table "comment_hierarchies", id: false, force: true do |t|
  t.integer "ancestor_id",   null: false
  t.integer "descendant_id", null: false
  t.integer "generations",   null: false
end

add_index "comment_hierarchies", ["ancestor_id", "descendant_id", "generations"], name: "comment_anc_desc_udx", unique: true
add_index "comment_hierarchies", ["descendant_id"], name: "comment_desc_idx"

create_table "comments", force: true do |t|
  t.string   "body"
  t.string   "author"
  t.string   "post_id"
  t.boolean  "deleted"
  t.boolean  "locked"
  t.datetime "created_at"
  t.datetime "updated_at"
end

编辑:我通过更改页面上的表单以从

发表新评论来修复它
<%= form_for([@post, @post.comments.build], :html => {:class => 'ui form'}) do |f| %>
          <div class="field">
            <%= f.text_area :body, placeholder: "Comment", style: "max-height: 100px;"%>
          </div>
          <p>
            <%= f.submit "Add Comment", class: "blue ui button" %>
          </p>
      <% end %>

<%= form_for([@post, Comment.new], :html => {:class => 'ui form'}) do |f| %>
          <div class="field">
            <%= f.text_area :body, placeholder: "Comment", style: "max-height: 100px;"%>
          </div>
          <p>
            <%= f.submit "Add Comment", class: "blue ui button" %>
          </p>
      <% end %>

【问题讨论】:

  • closure_tree 是什么?
  • 尝试&lt;%= c.inspect %&gt;&lt;%= c.attributes %&gt; 来查看返回的评论是否是表单的内置评论(没有id 值),或者它是否实际保存在数据库中。

标签: ruby-on-rails sqlite activerecord


【解决方案1】:

您能在此之前致电@post.comments.new 以呈现评论表单吗?这可能是在association_cache 中添加新的非持久记录。

为避免这种情况,您应该能够将评论实例化为Comment.new(post_id: @post.id)。这不应该将注释添加到关联缓存中。如果是这样,您真的不需要新的Comment 上的post_id。无论如何,您可能将它放在隐藏字段中。

【讨论】:

  • 谢谢,伙计。如果我删除一个表单以添加我在 cmets 列表之前放置的新评论,它可以正常工作。关于如何让它与表单一起工作的任何想法?
【解决方案2】:

您的数据库中似乎一条评论保留在您的数据库中。

c.body 可能返回 nil,它本身并不能定义您的数据库中没有评论记录。可能你之前没有验证或在控制台上手动跳过它。

c.inspect 将为您提供对象中数据的更详细的细分。

您如何确认您的数据库是空的? @post.comments.count 是否等于 0?

【讨论】:

    猜你喜欢
    • 2018-08-14
    • 1970-01-01
    • 2016-09-03
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    相关资源
    最近更新 更多