2012-05-21 36 views
0

我的車型有:如何動態查找嵌入的Mongoid文檔?

class Cali 
    include Mongoid::Document 
    field :license_expire_date, :type => String 
    field :license_issue_date, :type => String 
    embeds_one :address 
end 

class Address 
    include Mongoid::Document 
    field :state, :type => String 
    field :city, :type => String 
    embedded_in :cali, :inverse_of => :address 
end 

當我使用@fields = Cali.fields.keys,我只得到了兩個字段(expire_dateissue_date)。我沒有得到結果中的地址。有沒有一種方法可以找到嵌入的內容和其中的字段?

回答

4

Here'a如何獲取關聯元數據。

Mongoid ::關係::#反思reflect_on_all_associations - 見http://rdoc.info/github/mongoid/mongoid/Mongoid/Relations/Reflections

請注意,如果你要提供一個以上的宏作爲參數作爲當前書面reflect_on_all_associations,宏必須ARGS。 如果你想提供一個數組,它必須被噴濺,例如, *宏,如下面的測試。

以下是「舊API」,因此您應該使用上述代替。

Mongoid ::關係:: ClassMethods ::協會 - 見http://rdoc.info/github/mongoid/mongoid/Mongoid/Relations/ClassMethods:associations

測試/單元/ cali_test.rb

require 'test_helper' 

class CaliTest < ActiveSupport::TestCase 
    def setup 
    Cali.delete_all 
    end 

    test "mongoid fields" do 
    address = Address.new(state: 'NJ', city: 'New Providence') 
    cali = Cali.create(address: address) 
    assert_equal(1, Cali.count) 
    macros = [:has_one, :has_many, :belongs_to, :has_and_belongs_to_many, :embeds_one, :embeds_many, :embedded_in] 
    puts "Cali.reflect_on_all_associations(*macros):#{Cali.reflect_on_all_associations(*macros).inspect}" 
    puts "Address.reflect_on_all_associations(*macros):#{Address.reflect_on_all_associations(*macros).inspect}" 
    #puts "Old API - Cali.associations:#{Cali.associations}" 
    #puts "Old API - Address.associations:#{Address.associations}" 
    end 
end 

測試輸出

Run options: --name=test_mongoid_fields 

# Running tests: 

Cali.reflect_on_all_associations(*macros):[#<Mongoid::Relations::Metadata 
class_name:   Address, 
cyclic:    No, 
dependent:   None, 
inverse_of:   N/A, 
key:     address, 
macro:    embeds_one, 
name:     address, 
order:    nil, 
polymorphic:   No, 
relation:    Mongoid::Relations::Embedded::One, 
setter:    address=, 
versioned:   No> 
] 
Address.reflect_on_all_associations(*macros):[#<Mongoid::Relations::Metadata 
class_name:   Cali, 
cyclic:    No, 
dependent:   None, 
inverse_of:   address, 
key:     cali, 
macro:    embedded_in, 
name:     cali, 
order:    nil, 
polymorphic:   No, 
relation:    Mongoid::Relations::Embedded::In, 
setter:    cali=, 
versioned:   No> 
] 
. 

Finished tests in 0.008605s, 116.2115 tests/s, 116.2115 assertions/s. 

1 tests, 1 assertions, 0 failures, 0 errors, 0 skips