7

MongoMapperでクラス継承を使用して、より適切で整理された結果を得ようとしていますが、問題があります。

class Item
  include MongoMapper::Document

  key :name, String
end

class Picture < Item
  key :url, String
end

class Video < Item
  key :length, Integer
end

次のコマンドを実行すると、期待したものが返されません。

>> Item.all
=> [#<Item name: "Testing", created_at: Sun, 03 Jan 2010 20:02:48 PST -08:00, updated_at: Mon, 04 Jan 2010 13:01:31 PST -08:00, _id: 4b416868010e2a04d0000002, views: 0, user_id: 4b416844010e2a04d0000001, description: "lorem?">]
>> Video.all
=> [#<Video name: "Testing", created_at: Sun, 03 Jan 2010 20:02:48 PST -08:00, updated_at: Mon, 04 Jan 2010 13:01:31 PST -08:00, _id: 4b416868010e2a04d0000002, views: 0, user_id: 4b416844010e2a04d0000001, description: "lorem?">]
>> Picture.all
=> [#<Picture name: "Testing", created_at: Sun, 03 Jan 2010 20:02:48 PST -08:00, updated_at: Mon, 04 Jan 2010 13:01:31 PST -08:00, _id: 4b416868010e2a04d0000002, views: 0, user_id: 4b416844010e2a04d0000001, description: "lorem?">]

Item.allそれらはすべて同じ結果であり、それ自体、、、Pictureおよびを含むすべての結果をリストすることを期待しますVideo。ただし、アイテムが実際にである場合は、実行した場合ではなく、実行した場合Pictureに返品されるようにしたいと思います。意味がわかりますか?Picture.allVideo.all

ここで継承がどのように機能するかを誤解していますか?私がこの種の行動を再現するための最良の方法は何ですか?私はこれをどのように機能させたいかについてのガイドラインとしてこれ(ポイント2)に従おうとしています。Link.all彼はすべてのリンクを見つけるために走ることができ、から継承する他のすべてのクラスを含めることはできないと思いItemます。私が間違っている?

4

1 に答える 1

10

Itemリンク先の例は、モデルの完全な定義を示していないという点で、少し誤解を招く可能性があります(または、理解するのが難しい場合があります) 。_typeモデルで継承を使用するには、親モデルでキーを定義する必要があります。その後、MongoMapperは、そのキーをそのドキュメントの実際のクラスのクラス名に自動的に設定します。したがって、たとえば、モデルは次のようになります。

class Item
  include MongoMapper::Document

  key :name, String
  key :_type, String
end

class Picture < Item
  key :url, String
end

class Video < Item
  key :length, Integer
end

検索の出力(Pictureオブジェクトを作成したと仮定)は次のようになります。

>> Item.all
=> [#<Picture name: "Testing", _type: "Picture", created_at: Sun, 03 Jan 2010 20:02:48 PST -08:00, updated_at: Mon, 04 Jan 2010 13:01:31 PST -08:00, _id: 4b416868010e2a04d0000002, views: 0, user_id: 4b416844010e2a04d0000001, description: "lorem?">]
>> Video.all
=> []
>> Picture.all
=> [#<Picture name: "Testing", _type: "Picture", created_at: Sun, 03 Jan 2010 20:02:48 PST -08:00, updated_at: Mon, 04 Jan 2010 13:01:31 PST -08:00, _id: 4b416868010e2a04d0000002, views: 0, user_id: 4b416844010e2a04d0000001, description: "lorem?">]
于 2010-01-06T05:37:38.053 に答える