【问题标题】:how to implement relationships between models with mongoid如何用 mongoid 实现模型之间的关系
【发布时间】:2012-08-14 10:01:19
【问题描述】:

1º用户约翰有很多礼物

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º用户Anthony买礼物给John并下新订单

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

现在用户 Anthony 想要访问他所做的所有销售。

这里的挑战是用户可能有两个角色,买家或卖家。

我应该如何在 Antonio 可以访问其销售额的模型之间建立关系?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 mongoid


    【解决方案1】:

    模型结构

    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
    

    【讨论】:

    • 一份礼物怎么可以关联多个订单..你能给出任何相同的用例吗?
    • @hyperrjas okk .. 没问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多