2014-02-11 38 views
1

所以,我有兩個型號:如何判斷模型是否嵌入在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 

但對於這兩種方法我需要知道層級嵌入費率。有沒有一種方法可以確定層級是否爲嵌入模型,然後在事先不知道與層級關係的情況下找出嵌入的模型?

回答

2

你可以使用reflect_on_all_associations其中:

返回提供的所有宏元數據的關係。

所以,如果你說:

embedded_ins = M.reflect_on_all_associations(:embedded_in) 

你會得到Mongoid::Relations::Metadata實例的數組(可能爲空)在embedded_ins。然後,你可以說:

embedded_ins.first.class_name 

讓我們嵌入類的名稱

+0

我很喜歡這種方法,它比我建議的方式更穩健,謝謝! – alalani

+0

我在看'M.associations',但似乎不贊成,然後該方法的來源導致我'M.relations'這似乎沒有記錄。 'reflect_on_all_associations'至少有文件記錄。 –

+1

哦,很酷,是的,我發現文檔非常有限,所以我通過調用M.methods做了自己的窺探,然後通過我認爲可能有用的方法 – alalani

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 
相關問題