如何判断Mongoid中是否嵌入了模型?

时间:2014-02-11 19:38:11

标签: ruby-on-rails mongodb mongoid

所以我有两个模特:

#app/models/rate.rb
class Rate
  include Mongoid::Document

  embeds_many :tiers

  field :name
  # other fields...

end

#app/models/tier.rb
class Tier
  include Mongoid::Document

  embedded_in :rate

  field :name
  # other fields...

end

现在根据mongoid文档,我可以做以下几点来确定模型是否嵌入到另一个模型中:

rate.tiers.embedded?
=> true
Tier.reflect_on_association(:rate).macro
=> :embedded_in

但对于这两种方法,我需要知道Tiers嵌入在Rate中。有没有办法可以找出Tiers是否是嵌入式模型,然后在不事先知道它与Rate的关系的情况下找出它们嵌入的模型?

2 个答案:

答案 0 :(得分:2)

您可以使用reflect_on_all_associations

  

返回所提供的宏的所有关系元数据。

所以,如果你说:

embedded_ins = M.reflect_on_all_associations(:embedded_in)

您将在Mongoid::Relations::Metadata中获得embedded_ins个实例的数组(可能为空)。然后你可以说:

embedded_ins.first.class_name

获取我们嵌入的类的名称。

答案 1 :(得分:1)

我原本希望在这里找到答案http://mongoid.org/en/mongoid/docs/relations.html但遗憾的是并非所有关于关系的方法都记录在那里。以下是如何做到这一点:

# To get whether a class is embedded
Model.embedded?

# So in the case of Tiers I would do
Tier.embedded?
=> true

# To get the class that the object is embedded in
# Note, this assumes that the class is only embedded in one class and not polymorphic
klass = nil
object.relations.each do |k, v|
  if v.macro == 'embedded_in'
    klass = v.class_name
  end
end

# So in our case of Tiers and Rates I would do
tier = Tier.find(id)
if tier.embedded?
  rate = nil
  tier.relations.each do |k, v|
    if v.macro == 'embedded_in'
      rate = v.class_name # Now rate is equal to Rate
    end
  end
  rate.find(rate_id) # This will return the rate object with id = rate_id
end