开发者

mongo mapper with STI with more than one type?

I have a series of models all which inherit from a base model Properties

For ex开发者_如何学Goample Bars, Restaurants, Cafes, etc.

class Property
  include MongoMapper::Document

  key :name, String
  key :_type, String
end

class Bar < Property

What I'm wondering is what to do with the case when a record happens to be both a Bar & a Restaurant? Is there a way for a single object to inherit the attributes of both models? And how would it work with the key :_type?


I think you want a module here.

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!

This way you can let many models have the properties of a restaurant, without duplicating your code.

What you could also try, though I haven't experimented with it myself, is multiple levels of inheritance. e.g.:

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

Not sure off the top of my head whether MongoMapper supports this, but I don't see why it wouldn't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜