maeshimaの日記

メモ書きです

今週のrailscasts - Mongoid

ASCIIcasts - “Episode 238 - Mongoid”を見て。mongo_mapper の代換え プラグインである Mongoidについて。ドキュメント類がしっかりしてるそうな。

Mongoid

install

普通にgemで入れる。bson_extというJSONのバイナリ版を扱うgemも一緒に入れる必要がある。

その後

rails g mongoid:config

で mongoid 用の config ファイルを生成。自分の mongodbの設定を書く。

カラムの設定

mongoid をインストールすると、その後 model を生成したときに migration ファイルが作られなくなり、modelにmongodb用のカラムの設定が書かれるようになる。これは動的に変更可能(rake db:migrate のようなことは必要ない)。validationも普通に効くみたい。

embed

関連を使うには、普通にhas_many的な関連を使う方法と、親のDocumentに子をembedする方法の二種類がある。親経由で子を取得することしかないのであれば、後者の方がパフォーマンス的にいいんだろうね。

embedしたい場合は、親の方で

embeds_many :comments

子の方で

embedded_in :article, :inverse_of => :comments 

のようにするといいみたい。

embedした場合、子は親のDocument中に含まれるので、子のレコードの数を数えることはできなくなる。下記のように親経由じゃないとダメ。

Article.first.comments.count #=> 1

reference

has_many的な関連もちょっとやり方が異なる。

class Author  
  include Mongoid::Document  
  field :name  
  key :name  
  references_many :articles  
end

class Article  
  include Mongoid::Document  
  field :name  
  field :content  
  field :published_on, :type => Date  
  validates_presence_of :name  
  embeds_many :comments  
  referenced_in :author  
end  
  • key メソッドで primary key 的なカラムを指定
  • has_many -> references_many
  • belongs_to -> referenced_in