4

我希望能够在同一个模型中多次引用一个模型(has_many 关系)。例如,给定以下模型:

class MyModel
    include Mongoid::Document

    field :name, type: String
    has_many :main_efforts, :class_name => 'Effort', as: :effortable, dependent: :delete, autosave: true
    has_many :secondary_efforts, :class_name => 'Effort', as: :effortable, dependent: :delete, autosave: true

    validates_presence_of :name
end

class Effort
    include Mongoid::Document

    field :name, type: String
    belongs_to :effortable, polymorphic: true
    validates_presence_of :name
end

如您所见,Effort 模型被引用了两次。最初,我的 Effort 模型不是多态的,但似乎 Mongoid 无法确定该努力属于哪个集合(main_efforts 或 secondary_efforts)。因此,我使它成为多态的。然而,在使其成为多态之后,我的 main_efforts 和 secondary_efforts 字段始终是一个空数组。

在同一模型中多次引用多态模型的正确方法是什么(假设需要多态模型)?

4

1 回答 1

6

弄清楚了:

class MyModel
    include Mongoid::Document

    field :name, type: String
    has_many :main_efforts, :class_name => 'Effort', dependent: :delete, autosave: true, :inverse_of => :main_effort
    has_many :secondary_efforts, :class_name => 'Effort', dependent: :delete, autosave: true, :inverse_of => :secondary_effort

    validates_presence_of :name
end

class Effort
    include Mongoid::Document

    field :name, type: String
    belongs_to :main_effort, :class_name => 'Conop', :inverse_of => :main_efforts
    belongs_to :secondary_effort, :class_name => 'Conop', :inverse_of => :secondary_efforts
    validates_presence_of :name
end
于 2013-08-12T00:30:29.180 回答