如何动态查找嵌入的Mongoid文档?

时间:2012-05-21 12:19:53

标签: 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)。我没有得到结果中的地址。有没有办法可以找到嵌入的内容和里面的字段?

1 个答案:

答案 0 :(得分:4)

这里是如何获取关联元数据。

Mongoid :: Relations :: Reflections#reflect_on_all_associations - 请参阅http://rdoc.info/github/mongoid/mongoid/Mongoid/Relations/Reflections

请注意,如果要提供多个宏作为当前写入的reflect_on_all_associations的参数,则宏必须是args。 如果你想提供一个数组,它必须是splatted,例如*宏,如下面的测试。

以下是“旧API”,因此您应该使用上述内容。

Mongoid :: Relations :: ClassMethods :: associations - 请参阅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