ruby-on-rails - Rails 显示不存在的数据库记录

标签 ruby-on-rails sqlite activerecord

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

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

然后,我得到 #<Comment:0x007fe971c02800>如果我这样做也是c.attributes我明白了 {"id"=>nil, "body"=>nil, "author"=>nil, "post_id"=>37, "deleted"=>nil, "locked"=>nil, "created_at"=>nil, "updated_at"=>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 %>

最佳答案

您能否在此之前的某处调用 @post.comments.new 来呈现评论表单?这可能是在 association_cache 中添加新的非持久记录。

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

关于ruby-on-rails - Rails 显示不存在的数据库记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28588761/

相关文章:

mysql - 强制在 Rails 中重新连接 MySQL

ruby-on-rails - 在 Rails 表单对象中处理日期的最佳方式是什么

ruby-on-rails - Ruby on Rails 路由,如何强制更改子域/域

ruby-on-rails - 仅脚手架 Rails 中的 View 文件。可能的?

ruby-on-rails - :onclick doesn't work in button_to

android - CREATE VIEW of UNION 两个表,合并行

ruby - 有没有一种干净的方法来测试 Rspec 中的 ActiveRecord 回调?

ruby-on-rails - 调用错误方法时出现 "undefined method ` 错误 ' for nil:NilClass"

sqlite - 如何在sqlite中使用where和group by提高查询性能

qt - SELECT COUNT(*) 在 QML 中不起作用