Mongoid has_many关系返回没有值

时间:2013-05-23 09:28:20

标签: ruby-on-rails mongoid

假设用户可以向其他用户赠送礼物。礼物和用户之间有两种关系(一种作为发送者,另一种作为接收者)。

接收器部分似乎没有按照以下代码工作,其中创建礼物但在调用关联时未检索到:

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?

2 个答案:

答案 0 :(得分:0)

您必须为has_many礼物关系提供 inverse_of 。 为了处理名为gifts_sent的第二个关系,你必须在定义关系时提及 foreign_key

class User
  include Mongoid::Document

  has_many :gifts, inverse_of: :user
  has_many :gifts_sent, :foreign_key => :assign_whatever_field, class_name: "Gift", inverse_of: :sender, 
end

礼物模型将是

class Gift
  include Mongoid::Document

  belongs_to :user,   inverse_of: :gifts
  belongs_to :sender,:foreign_key => :assign_whatever_field, inverse_of: :gifts_sent, class_name: "User"
end

答案 1 :(得分:0)

有必要在用户模型中包含反向关系:

class User
  include Mongoid::Document

  has_many :gifts,      inverse_of: :user
  has_many :gifts_sent, inverse_of: :sender, class_name: "Gift"
end

class Gift
  include Mongoid::Document

  belongs_to :user,   inverse_of: :gifts
  belongs_to :sender, inverse_of: :gifts_sent, class_name: "User"
end