1

我有一系列的从一个基础模型Properties具有多种类型的STI的mongo映射器?

例如继承模型所有Bars, Restaurants, Cafes, etc.

class Property 
    include MongoMapper::Document 

    key :name, String 
    key :_type, String 
end 

class Bar < Property 

什么我不知道是用的情况下做什么时,记录恰好是一个既酒吧& a餐厅?有没有办法让一个对象继承两个模型的属性?它将如何与密钥一起工作:_type?

回答

2

我想你想要一个模块在这里。

class Property 
    include MongoMapper::Document 

    key :name, String 
    key :_type, String 
end 

module Restaurant 
    def serve_food 
    puts 'Yum!' 
    end 
end 

class Bar < Property 
    include Restaurant 
end 

Bar.new.serve_food # => Yum! 

这样,您可以让很多模型具有餐厅的属性,而无需重复您的代码。

你也可以尝试一下,尽管我自己也没有尝试过,但它是多层次的继承。例如:

class Property 
    include MongoMapper::Document 

    key :name, String 
    key :_type, String 
end 

class Restaurant < Property 
    key :food_menu, Hash 
end 

class Bar < Restaurant 
    key :drinks_menu, Hash 
end 

不知道我的头顶是否MongoMapper支持这个,但我不明白为什么它不会。

+0

它不是模型继承其他模型,我理解如何做到这一点,我想知道的是特殊情况下特定记录的行为像两个模型之间的混合。 – holden 2010-03-16 09:05:41

+0

在我的最后一个例子中就是这种情况 - 保存的酒吧记录将包含food_menu和drinks_menu。你的意思是不同的? – PreciousBodilyFluids 2010-03-16 13:57:52

相关问题