質問

私は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.allを実行する場合、私はVideo.allを実行していない場合、それが返されたいです。あなたは私が何を意味するか参照していますか?

私は、継承が、ここでどのように機能するかを誤解だろうか?私は場合の挙動のこの種を複製するための最良の方法は何ですか?私は従うことをしようとしています<のhref =「http://railstips.org/2009/12/18/why-i-think-mongo-is-to-databases-what-rails-was-to-frameworks」のrel =私はこの仕事をする方法の指針として「noreferrer」>このを(ポイント2)。私は彼がすべてのリンクを見つけるためにLink.allを実行し、Itemから継承する他のすべてのクラスを含めることはできませんと仮定します。私が間違っているのでしょうか?

役に立ちましたか?

解決

それは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?">]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top