你有沒有在Mongoid中試過繼承? http://mongoid.org/en/mongoid/docs/documents.html#inheritance
以下測試做了我認爲你想要做的事情,其中保存了文件,歷史和自然對象 ,並將其從保留類型的集合中存儲和提取。 我希望你覺得這個有用。
應用程序/模型/興趣
class Interest
include Mongoid::Document
field :description, type: String
field :coordinates, type: String
end
應用程序/模型/文化
class Culture < Interest; end
應用程序/模型/歷史
class History < Interest; end
應用程序/模型/自然
class Nature < Interest; end
測試/單元/ interest_test.rb
require 'test_helper'
require 'pp'
class InterestTest < ActiveSupport::TestCase
def setup
Interest.delete_all
Culture.delete_all
History.delete_all
Nature.delete_all
end
test "version" do
puts "\nMongoid::VERSION:#{Mongoid::VERSION}\nMoped::VERSION:#{Moped::VERSION}"
end
test "inheritance" do
Culture.create(description: "a culture site", coordinates: "40.7577° N, 73.9857° W")
History.create(description: "a history site", coordinates: "40.7577° N, 73.9857° W")
Nature.create(description: "a nature site", coordinates: "40.7577° N, 73.9857° W")
array_type_sites = ["nature", "culture", "history"]
@sites = Culture.where(:coordinates => {"$ne" => "", "$ne" => nil}).to_a
if array_type_sites.include?("nature")
@sitesNature = Nature.where(:coordinates => {"$ne" => "", "$ne" => nil}).to_a
@sites += @sitesNature
end
if array_type_sites.include?("culture")
@sitesCulture = Culture.where(:coordinates => {"$ne" => "", "$ne" => nil}).to_a
@sites += @sitesCulture
end
Interest.collection.insert(@sites.collect{|site|site.serializable_hash})
puts
pp Interest.all.to_a
end
end
耙測試
Run options:
# Running tests:
[1/2] InterestTest#test_inheritance
[#<Culture _id: 53dfd43b7f11ba43ef000001, description: "a culture site", coordinates: "40.7577° N, 73.9857° W", _type: "Culture">,
#<History _id: 53dfd43b7f11ba43ef000002, description: "a history site", coordinates: "40.7577° N, 73.9857° W", _type: "History">,
#<Nature _id: 53dfd43b7f11ba43ef000003, description: "a nature site", coordinates: "40.7577° N, 73.9857° W", _type: "Nature">]
[2/2] InterestTest#test_version
Mongoid::VERSION:3.1.6
Moped::VERSION:1.5.2
Finished tests in 0.084751s, 23.5985 tests/s, 0.0000 assertions/s.
2 tests, 0 assertions, 0 failures, 0 errors, 0 skips
ruby -v: ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-darwin12.0]