Mongoid:通过has_many不止一次引用相同的模型

时间:2013-08-10 15:39:17

标签: ruby mongoid mongoid3

我希望能够在同一个模型中多次引用模型(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字段始终是一个空数组。

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

1 个答案:

答案 0 :(得分: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