【问题标题】:deleting embedded documents with mongoid使用 mongoid 删除嵌入的文档
【发布时间】:2011-11-02 08:01:43
【问题描述】:

我正在使用 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)似乎会将其从内存中删除,而不是从数据库中删除。任何见解将不胜感激!

【问题讨论】:

  • 嗨。你找到答案了吗?非常感谢任何帮助
  • 抱歉 - 不 - 这是不久前的事了,我还没有从事这个项目

标签: ruby-on-rails mongoid


【解决方案1】:

请发布您的 rails 版本和 gem 的版本。我已经用 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)

【讨论】:

    猜你喜欢
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多