如何动态查找嵌入的 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(。我在结果中没有得到地址。有没有办法找到嵌入的内容和其中的字段?

下面介绍如何获取关联元数据。

Mongoid::关系::反射#reflect_on_all_associations - 见 http://rdoc.info/github/mongoid/mongoid/Mongoid/Relations/Reflections

请注意,如果要提供多个宏作为参数,以reflect_on_all_associations当前编写的内容,则宏必须是参数。如果要提供一个数组,则必须对其进行拼接,例如 *宏,如以下测试所示。

以下是针对"旧 API"的,因此您应该改用上述内容。

Mongoid::Relations::ClassMethods::Association - 参见 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

最新更新