ruby-on-rails - 删除带有mongoid的嵌入式文档

标签 ruby-on-rails mongoid

我正在用mongoid构建我的第一个应用程序,但是在删除嵌入式资源时遇到了麻烦。我有以下模型:

class Article
 include Mongoid::Document
 field :body
 embeds_many :comments

等等..
class Comment
 include Mongoid::Document
 field :body
 embedded_in :article, :inverse_of => :comments
end

我不明白为什么我不能从文章中删除评论
    ruby-1.9.2-p290 :043 > @article.comments
    => [#<Comment _id: 4eb0e991a27d201ded000038, _type: nil, body: "foo", score: nil>] 
    ruby-1.9.2-p290 :045 > @article.comments.first.destroy
    => true 
    ruby-1.9.2-p290 :046 > @article.comments
    => [] 
    ruby-1.9.2-p290 :047 > @article.save
    => true 
    ruby-1.9.2-p290 :049 > @article.reload
    => #<Article _id: 4eb0e991a27d201ded000037, _type: nil, body: "foo", title: .... 
    ruby-1.9.2-p290 :050 > @article.comments
    => [#<Comment _id: 4eb0e991a27d201ded000038, _type: nil, body: "foo", score: nil>] 

在嵌入式文档上调用destroy(或delete)似乎是将其删除在内存中,而不是从数据库中删除。任何见解将不胜感激!

最佳答案

请发布您的rails版本和您的gems版本。我已经用Rails 3.2.3检查了您的设置:

Loading development environment (Rails 3.2.3)
1.9.3-p0 :001 > @article = Article.new(:body => 'articleBodyText')
 => #<Article _id: 4f9d90c7f15fefb3a0000001, _type: nil, body: "articleBodyText"> 
1.9.3-p0 :002 > @article.save
 => true 
1.9.3-p0 :003 > @article.comments = [Comment.new(:body => 'commentBodyText')]
 => [#<Comment _id: 4f9d90edf15fefb3a0000002, _type: nil, body: "commentBodyText">] 
1.9.3-p0 :004 > @article.save
 => true 
1.9.3-p0 :005 > @article.comments
 => [#<Comment _id: 4f9d90edf15fefb3a0000002, _type: nil, body: "commentBodyText">] 
1.9.3-p0 :006 > @article.reload
 => #<Article _id: 4f9d90c7f15fefb3a0000001, _type: nil, body: "articleBodyText"> 
1.9.3-p0 :007 > @article.comments
 => [#<Comment _id: 4f9d90edf15fefb3a0000002, _type: nil, body: "commentBodyText">] 
1.9.3-p0 :008 > @article.comments.first.destroy
 => true 
1.9.3-p0 :009 > @article.comments
 => [] 
1.9.3-p0 :010 > @article.save
 => true 
1.9.3-p0 :011 > @article.reload
 => #<Article _id: 4f9d90c7f15fefb3a0000001, _type: nil, body: "articleBodyText"> 
1.9.3-p0 :012 > @article.comments
 => [] 
1.9.3-p0 :013 > 

Gemfile的相关部分:
gem "mongoid", "~> 2.4"
gem "bson_ext", "~> 1.5"

Gemfile.lock的相关部分:
rails (3.2.3)
mongo (1.6.2)
mongoid (2.4.8)
bson (1.6.2)
bson_ext (1.6.2)

关于ruby-on-rails - 删除带有mongoid的嵌入式文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7977270/

相关文章:

ruby-on-rails - 为每个环境指定 rails 4 主机

javascript - jQuery 如果带有选择的表单已填写,则显示 div

ruby-on-rails - 使用 MongoID 的不区分大小写的查询条件

python - python 中的 mongodb 列约束,如 ruby​​ mongoid

ruby-on-rails - 自动用星号标记必填字段,不起作用

ruby-on-rails - 在 Rails 3 中从 SQl 切换到 MongoDB

ruby-on-rails - 在 Rails 3 中自定义 Rspec 生成器

jquery - Rails3/will_paginate/Ajax - 下一个/上一个链接无法正常工作(这是一个错误吗?)

javascript - 可编辑的动态目标值

ruby-on-rails - 在 Rails 中使用 MongoID 保存二进制数据