2

I am very new to mongodb/mongoid and was wondering about the best way to architect a system that enables users to review products. User and Product will be individual collections. But they both need access to the Review model for displaying the reviews they made on both the User and Product page. Should I create an linked 1 (product) -N (reviews) relationship with an embedded 1(user) - 1(review) relationship? Is this the correct way to do this?

User model

class User
  include Mongoid::Document

  field :name, type: String
  field :email, type: String

  embeds_many :reviews, cascade_callbacks: true
end

Product model

class Product
  include Mongoid::Document

  field :name, type: String
  field :price, type: Float

  has_many :reviews, dependent: :destroy
end

Review model

class Review
  include Mongoid::Document

  field :rating, type: Integer

  belongs_to :product
  embedded_in :user
end

Thanks

perseverance
  • 6,372
  • 12
  • 49
  • 68

1 Answers1

0

Its not the correct way to define the model structures as you can't access embedded document directly and you will not able to create a refrential relationship bwtween product and review. The correct structure will be

User model

class User
  include Mongoid::Document

  field :name, type: String
  field :email, type: String

  has_many :reviews, dependent: :destroy
end

Product model

class Product
  include Mongoid::Document

  field :name, type: String
  field :price, type: Float

  has_many :reviews, dependent: :destroy
end

Review model

class Review
  include Mongoid::Document

  field :rating, type: Integer

  belongs_to :product
  belongs_to :user
end
abhas
  • 5,193
  • 1
  • 32
  • 56
  • Wouldn't this be slow because you need to do a join each time you access the data? – perseverance Nov 20 '12 at 22:29
  • ya it will be as compared to the embeds relation but you need data for both user and product with respect to review...it will make one query faster which is embedded but another one really messy and time taking. We face the same issue in post and comment structure generally when we embeds comment into post and when you have to find out comments made by user its a very slow query – abhas Nov 21 '12 at 04:31