最近我遇到了无法解决的问题(或谷歌正确)。首先,这是文件:
#Counter.rb
class Counter
include Mongoid::Document
embeds_many :pointing, as: :goodvs, store_as: "goodvs"
embeds_many :pointing, as: :badvs, store_as: "badvs"
accepts_nested_attributes_for :pointing
field :name, type: String
field :champId, type: Integer
end
#Pointing.rb
class Pointing
include Mongoid::Document
belongs_to :counter
accepts_nested_attributes_for :counter
field :name, type: String
field :votes, type: Integer
field :lane, type: String
end
我想在Counter类double中嵌套Pointing类来制作这样的结构:
{
name: 'sth',
champId: 1,
goodvs: [{
name: 'sthsth'
votes: 1
lane: 'top'
},
{
name: 'sthsth2'
votes: 4
lane: 'bot'
}],
badvs: [{
name: 'sthsth'
votes: 1
lane: 'mid'
}]
}
任何人都有任何解决方法如何做到这一点?我可以为仅使用过一次的嵌套属性设置正常结构,但我不知道如何在这种情况下正确地执行此操作。
答案 0 :(得分:1)
我刚刚开始搞乱mongo / mongoid,但看起来你的类定义有点不对劲。详细信息参考Mongoid Relations docs
embedded_in
使用embeds_many
关系。 belongs_to
与has_many
一起使用。
class Pointing
include Mongoid::Document
embedded_in :counter
field :name, type: String
field :votes, type: Integer
field :lane, type: String
end
如果没有解决它...我使用class_name
指向实际的类,设置自定义关系名称略有不同。记录as:
选项,当子文档可以属于许多父母时使用,但是我没有足够使用它来说明这是实际差异还是仅仅是样式。
class Counter
include Mongoid::Document
embeds_many :goodvs, class_name: "Pointing"
embeds_many :badvs, class_name: "Pointing"
accepts_nested_attributes_for :goodvs, :badvs
field :name, type: String
field :champId, type: Integer
end
然后检索我用<:p>创建的对象
Counter.each do |c|
log 'counter name', c.name, c.id
log 'goodv', c.goodvs
log 'goodv first', c.goodvs.first.name, c.goodvs.first.id
log 'badvs', c.badvs
log 'badvs first', c.badvs.first.name, c.badvs.first.id
end
结果:
counter name [sth] [53cfcee66fcb2d2db5000001]
goodv [#<Pointing:0x00000601a395b0>] [#<Pointing:0x00000601a393f8>]
goodv first [mee] [53cfcee66fcb2d2db5000002]
badvs [#<Pointing:0x00000601a37468>] [#<Pointing:0x00000601a372b0>]
badvs first [mee] [53cfcee66fcb2d2db5000002]
所以不同的Pointing
对象引用,但goodvs
和badvs
包含相同的mongo文档。