我对mongoid完全陌生。是否有类关系定义中的任何选项或内容来启用此功能?
class Band
include Mongoid::Document
field :name, type:String
has_and_belongs_to_many :members
end
class Member
include Mongoid::Document
field :name, type: String
has_and_belongs_to_many :bands
end
andy = Member.new(name: 'Andy Bell')
ride = Band.new(name: 'Ride')
ride.members << andy
oasis = Band.new(name: 'Oasis')
oasis.members << andy
andy.bands #=> returns: [] (empty array)
andy.band_ids #=> returns: [BSON::ObjectId('53586a786d6163870c030000'), BSON::ObjectId('53586a786d6163870c040000')]
答案 0 :(得分:1)
我不确定但是从the docs here读取有重新加载方法,这有帮助吗?:
如果您在作为关系一部分的模型上使用默认范围 你必须像has_many,has_and_belongs_to_many或embeds_many一样 重新加载关系以重新应用范围。这很重要 请注意,如果您在关系中更改文档的值 影响其在范围关系中的可见性。
class Label
include Mongoid::Document
embeds_many :bands
end
class Band
include Mongoid::Document
field :active, default: true
embedded_in :label
default_scoped where(active: true)
end
label.bands.push(band)
label.bands #=> [ band ]
band.update_attribute(:active, false)
label.bands #=> [ band ] Must reload.
label.reload.bands #=> []