MongoMapper中的單個集合繼承(SCI)自動生成選擇, 前例如下產生相同的結果。
p Game.where(_type: 'TestVisual').all
p TestVisual.all
參見mongomapper/lib目錄/ mongo_mapper /插件/ sci.rb - MongoMapper ::插件::科學:: ClassMethods#查詢
然而,MongoMapper不會自動生成的子類協會根據基類的協會, 和我不認爲這應該是預期的。
請注意,SCI將子類和基類放在同一個MongoDB集合中。 如果這不是你想要的,你應該考慮其他模塊化機制。
您可以自己爲關聯訪問器方法定義以下方法,這對於您的目的來說可能足夠了嗎? 對於其他關聯方法(如append或push),父方法可能是可行的。
class Maestra
include MongoMapper::Document
key :name, String
many :games
def test_visuals
games.where(_type: 'TestVisual')
end
end
測試/單元/ test_visual_test.rb
require 'test_helper'
def ppp(obj)
puts obj.inspect.gsub(/, ([^#])/, ",\n\t\\1").gsub(/, #/, ",\n #")
end
class TestVisualTest < ActiveSupport::TestCase
def setup
Maestra.delete_all
Game.delete_all
end
test "inheritance" do
maestra = Maestra.create(name: 'Fiona')
maestra.games << Game.create(incorrect: 1, correct: 9, time_to_complete: 60)
maestra.games << TestVisual.create(incorrect: 2, correct: 8, time_to_complete: 61)
ppp maestra.games.to_a
ppp maestra.test_visuals.to_a
end
end
輸出
Run options: --name=test_inheritance
# Running tests:
[#<Game _id: BSON::ObjectId('4ff7029a7f11ba6e43000002'),
_type: "Game",
correct: 9,
created_at: Fri,
06 Jul 2012 15:22:02 UTC +00:00,
incorrect: 1,
maestra_id: BSON::ObjectId('4ff7029a7f11ba6e43000001'),
time_to_complete: 60,
updated_at: Fri,
06 Jul 2012 15:22:02 UTC +00:00>,
#<TestVisual _id: BSON::ObjectId('4ff7029a7f11ba6e43000003'),
_type: "TestVisual",
correct: 8,
created_at: Fri,
06 Jul 2012 15:22:02 UTC +00:00,
incorrect: 2,
maestra_id: BSON::ObjectId('4ff7029a7f11ba6e43000001'),
time_to_complete: 61,
updated_at: Fri,
06 Jul 2012 15:22:02 UTC +00:00>]
[#<TestVisual _id: BSON::ObjectId('4ff7029a7f11ba6e43000003'),
_type: "TestVisual",
correct: 8,
created_at: Fri,
06 Jul 2012 15:22:02 UTC +00:00,
incorrect: 2,
maestra_id: BSON::ObjectId('4ff7029a7f11ba6e43000001'),
time_to_complete: 61,
updated_at: Fri,
06 Jul 2012 15:22:02 UTC +00:00>]
.
Finished tests in 0.026661s, 37.5080 tests/s, 0.0000 assertions/s.
1 tests, 0 assertions, 0 failures, 0 errors, 0 skips
哇真棒!非常感謝村上加里。 Superashi! – Trip