分配属于关联时未定义的方法“关系”

Undefined method `relations` when assigning belongs to association

我有 2 个模型:

class Annotation
  include Mongoid::Document
  belongs_to :event
  field :desc, type: String
end

class Event::Event
  include Mongoid::Document
  has_many :annotations
end

然后我在 rails 控制台中通过键入创建了 2 个对象:

a = Annotation.new
e = Event::Event.new

现在一切都很好,但是当我这样做的时候

a.event = e

我收到以下错误:

NoMethodError: undefined method `relations' for Event:Module

为什么会出现此错误以及如何解决?谢谢。

试试这个:

class Annotation
  include Mongoid::Document
  belongs_to :event, class_name: 'Event::Event'
  ...
end

默认情况下,belongs_to 关联假定关联对象的类型为 Event,但 Event 是一个模块。 Class 这里的名字应该是 Event::Event。因此,需要在关系中指定。

如果有帮助请告诉我。