hyperrjas
hyperrjas

Reputation: 10744

how to implement relationships between models with mongoid

1º user John has many gifts

user.rb

class User
  include Mongoid::Document
  has_many :gifts, dependent: :destroy, :autosave => true
  has_many :orders, dependent: :destroy, :autosave => true
 end

gift.rb

 class Gift
      include Mongoid::Document
      belongs_to :user
      has_many :orders ,dependent: :destroy, :autosave => true
     end

2º user Anthony buy a gift to John and make a new order

class Order
   include Mongoid::Document
   belongs_to :gift
   belongs_to :user
  end

Now the user Anthony wants to access all his sales made.

The challenge here is that a user may have two roles, buyer or a seller.

How should I develop relationships between models that Antonio can access his sales made?

Upvotes: 0

Views: 853

Answers (1)

Sandip Ransing
Sandip Ransing

Reputation: 7723

Models structure

class User
  include Mongoid::Document

  has_many :gifts, dependent: :destroy, :autosave => true
  has_many :orders, dependent: :destroy, :autosave => true
end

class Gift
  include Mongoid::Document

  belongs_to :user
  belongs_to :gifted_to, :class_name => 'User'

  has_one :order ,dependent: :destroy, :autosave => true
end

class Order
  include Mongoid::Document

  belongs_to :gift
  # below associtation is just for quicker ref 
  # otherwise you can have access to it via gift also
  belongs_to :user
end

Upvotes: 2

Related Questions