如何在Mongoid中为引用的子元素重用相同的类?

时间:2014-01-17 00:13:31

标签: ruby mongodb twitter mongoid

我有两个这样的模型

class User
  include Mongoid::Document

  has_one :tweet
  has_many :tweet
end

class Tweet
    include Mongoid::Document
    belongs_to :created_by,     class_name: "User"

end

当然,这个不起作用,但这是我想要的。基本上,推文应该有一个created_by和许多提到的用户。例如,如果推文是这样的

“今天我遇到了@ user1和@ user2”

Tweets集合应该是这样的

{
 "created_by_id" : "ObjectId("of created user"),
 "mentioned_user_ids : [ObjectId("user1"), ObjectId("user2")]
}

Users集合应该是这样的

{
 "_id" : ObjectId("of created user")
},
{
 "_id" : ObjectId("user1")
},
{
 "_id" : ObjectId("user2")
}

1 个答案:

答案 0 :(得分:1)

这应该有效:

class User
  include Mongoid::Document

  has_many :owner_tweets, class_name: 'Tweet', inverse_of: :created_by
end

class Tweet
  include Mongoid::Document

  belongs_to :created_by, class_name: "User", inverse_of: :owner_tweets
  has_and_belongs_to_many :mentioned_users, class_name: "User", inverse_of: nil
end

owner = User.create
user1 = User.create
user2 = User.create

tweet = Tweet.create( owner_id: owner.id )
tweet.mentioned_users << user1
tweet.mentioned_users << user2

tweet
=> #<Tweet _id: 52da59abd9a0d1fda4000003, created_by_id: "52da5985d9a0d1fda4000001", mentioned_user_ids: ["52da59a2d9a0d1fda4000002", "52da59a2d9a0d1fda4000003"]> 
owner
=> #<User _id: 52da5985d9a0d1fda4000001, >

有关详细信息:http://mongoid.org/en/mongoid/docs/relations.html