0

I have two models:

class Post
 include MongoMapper::Document

 many :comments

 key :content, String
end

and

class Comment
  include MongoMapper::Document

  belongs_to :post

  key :post_id, ObjectId
  key :content, String

end

in a rails console session I can find all Posts:

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

and all comments associated with a Post:

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

however, the following query strangely returns an empty array

Comment.all # -> []

Why? How can I get a list of all comments independently of the posts?

4

1 回答 1

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

$耙子测试

运行选项:

# 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]
于 2013-07-10T19:34:21.570 回答