嵌入式mongoid引用

时间:2012-02-14 04:37:52

标签: mongodb reference ruby-on-rails-3.1 mongoid foreign-key-relationship

我的User模型has_and_belongs_to_many :conversations

Conversation模型embeds_many :messages

Message模型需要有senderrecipient

我无法在Mongoid documentation找到referenced_in

如何在邮件中分配用户?我尝试按照与this implementation类似的内容,但不断获取BSON::InvalidDocument: Cannot serialize an object of class Mongoid::Relations::Referenced::In into BSON.

2013年11月更新reference_in不再适用于Mongoid 3.0?更改为belongs_to,它似乎也一样。

1 个答案:

答案 0 :(得分:3)

事实证明,引用Message的{​​{1}}的结构是合适的,序列化错误与将用户与对话相关联有关。这是我的结构和创建步骤。感谢任何关于更好实践的反馈,谢谢。

class User
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Paranoia

  has_and_belongs_to_many :conversations
end
class Conversation
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Paranoia

  has_and_belongs_to_many :users
  embeds_many :messages
end
class Message
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Paranoia

  embedded_in :conversation
  embeds_one :sender, class_name: 'User'
  embeds_one :recipient, class_name: 'User'

  field :content
  field :read_at, type: DateTime
  field :sender_deleted, type: Boolean, default: false
  field :recipient_deleted, type: Boolean, default: false

  belongs_to :sender, class_name: "User", inverse_of: :sender, foreign_key: 'sender_id'
  belongs_to :recipient, class_name: "User", inverse_of: :recipient, foreign_key: 'recipient_id'
end

在我尝试User之前,适当的方式是@conversation.build(user_ids: [@user_one,@user_two])。然后你可以简单地@conversation.users.concat([@user_one,@user_two])