2012-06-30 76 views
0

我有一個是由Game類繼承的TestVisual類:正如你可以看到它屬於臘使用共享關係的繼承類最正確的方法?

class TestVisual < Game 
    include MongoMapper::Document 
end 

class Game 
    include MongoMapper::Document   

    belongs_to :maestra 

    key :incorrect,   Integer 
    key :correct,   Integer 
    key :time_to_complete, Integer 

    key :maestra_id, ObjectId 

    timestamps! 

end 

所以我可以做Maestra.first.games返回[]

但我不能給Maestra.first.test_visuals因爲它返回undefined method test_visuals

由於我與TestVisuals具體的工作,這是我非常希望拉什麼,但仍然有它共享其父級遊戲類的屬性。

這是可能與Mongo。如果不是或者沒有必要,是否還有其他更好的方法可以從Maestra到達TestVisual對象並且仍然繼承Game?

回答

1

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 
+0

哇真棒!非常感謝村上加里。 Superashi! – Trip