Mongomapper查询'belongs_to'模型

时间:2013-05-22 19:03:34

标签: ruby-on-rails mongodb mongomapper

我有两种模式:

class Post
 include MongoMapper::Document

 many :comments

 key :content, String
end

class Comment
  include MongoMapper::Document

  belongs_to :post

  key :post_id, ObjectId
  key :content, String

end

在rails控制台会话中,我可以找到所有帖子:

Post.all # -> [#<Post _id: BSON::ObjectId('519b0b613…

以及与帖子相关的所有评论:

post = Post.first # -> #<Post _id: BSON::ObjectId('519b0b613e477b…
post.comments     # -> [#<Comment _id: BSON::ObjectId('519d14f93e…

但是,以下查询奇怪地返回一个空数组

Comment.all # -> []

为什么呢?如何独立于帖子获取所有评论的列表?

1 个答案:

答案 0 :(得分:0)

对于完全按照你的帖子的模型,它适用于我,如下面的测试所示, 运行rails(3.2.13),mongo_mapper(0.12.0),mongo(1.6.4)。下次请发布完整的最小脚本,你可能只是有一个简单的错误。

测试/单元/ post_test.rb

require 'test_helper'

class PostTest < ActiveSupport::TestCase
  def setup
    Post.delete_all
    Comment.delete_all
  end

  test "post and comment" do
    post = Post.create(:content => 'Twas brillig')
    comment = Comment.create(:post_id => post.id, :content => 'and the slythy toves')
    post.comments << comment
    assert_equal 1, Post.count
    assert_equal 1, Comment.count
    puts
    puts "all posts: #{Post.all.inspect}"
    puts "first post comments: #{Post.first.comments.inspect}"
    puts "all comments: #{Comment.all.inspect}"
  end
end

$ rake test

运行选项:

# Running tests:

[1/1] PostTest#test_post_and_comment
all posts: [#<Post _id: BSON::ObjectId('51ddb56a7f11ba9bbf000001'), content: "Twas brillig">]
first post comments: [#<Comment _id: BSON::ObjectId('51ddb56a7f11ba9bbf000002'), content: "and the slythy toves", post_id: BSON::ObjectId('51ddb56a7f11ba9bbf000001')>]
all comments: [#<Comment _id: BSON::ObjectId('51ddb56a7f11ba9bbf000002'), content: "and the slythy toves", post_id: BSON::ObjectId('51ddb56a7f11ba9bbf000001')>]
Finished tests in 0.036030s, 27.7546 tests/s, 0.0000 assertions/s.
1 tests, 0 assertions, 0 failures, 0 errors, 0 skips

ruby -v: ruby 2.0.0p195 (2013-05-14 revision 40734) [x86_64-darwin12.3.0]