假设用户可以在其中向其他用户赠送礼物的应用程序。礼物和用户之间有两种关系(一种是发送者,另一种是接受者)。
根据以下代码,接收器部分似乎无法正常工作,其中在调用关联时创建了礼物但未检索到:
require 'rubygems'
require 'mongoid'
Mongoid.load!("./config/mongoid.yml")
class User
include Mongoid::Document
has_many :gifts
has_many :gifts_sent, class_name: "Gift", as: :sender
end
class Gift
include Mongoid::Document
belongs_to :user, inverse_of: :gifts
belongs_to :sender, inverse_of: :gifts_sent, class_name: "User"
end
alice = User.create!
bob = User.create!
gift = Gift.create! sender: alice, user: bob
puts Gift.where(sender_id: alice.id).count # => 1 (nice)
puts alice.gifts_sent.count # => 0 (not so nice)
应该如何定义关联使最后一行输出1?