enRai
enRai

Reputation: 681

How to store ObjectID in MongoDb without references?

I have three models:

class User
  include Mongoid::Document
  field :name, :type => String

  has_many :comments
  embeds_many :posts
end

class Post
  include Mongoid::Document
  field :title, :type => String
  field :body, :type => String

  embeds_many :comments
  belongs_to :user
end

class Comment
  include Mongoid::Document
  field :text, :type => String

  belongs_to :user
  embedded_in :post
end

And I have this error:

Referencing a(n) Comment document from the User document via a relational association is not allowed since the Comment is embedded.

Ok, thats right. But how can I store, who wrote a comment?

Upvotes: 1

Views: 570

Answers (1)

Ron
Ron

Reputation: 1166

The belongs_to user in the Comment is what's throwing it off. Just use a normal field to store the foreign key.

class Comment
  include Mongoid::Document

  embedded_in :post

  field :text, :type => String
  field :commenter_id
end

Upvotes: 2

Related Questions