最近MongoDBに興味があるのでRails3から触ってみることにした。
今回はObject-Document-Mapper(ODM)にMongoidを使ってみる。
前にMongoDBのODMにMongoMapperを使おうとしていたのだが、うまくインストールできなかったことがあった。
MongoDB触ってみる - 情報技術漫才誌
その時コメントでid:Kirikaさんから「Mongoidのほうがオヌヌメ」と言われて調べてみたら確かにMongoidが(検索数的に)よさげだったのでMongoidを使ってみることに。
前回のMongoMapper挑戦時にMongoDBがすでにインストール済みなので、インストールはこれだけ。
% gem install mongoid -r
Railsから使うのであればGemfileに書いておく。
% vim Gemfile gem 'mongoid'を追加して保存 % bundle install
準備ができたらgenerateを使ってモデルを作成
% rails generate model model_name Mongoid config not found. Create a config file at: config/mongoid.yml to generate one run: rails generate mongoid:config Mongoid preload_models is set to false. If you are using inheritance in your application model please set this to true or you will experience querying inconsistencies in dev mode. Note that this will severely decrease performance in dev mode only. invoke mongoid create app/models/model_name.rb invoke test_unit create test/unit/model_name_test.rb create test/fixtures/model_names.yml
作ったモデルの確認
%vim app/models/model_name.rb class ModelName include Mongoid::Document end
モデルにinclude Mongoid::Documentがされているのがわかる。
ちなみにモデルを削除する場合はdestroyを使ってモデルを削除
% rails destroy model model_name Mongoid config not found. Create a config file at: config/mongoid.yml to generate one run: rails generate mongoid:config Mongoid preload_models is set to false. If you are using inheritance in your application model please set this to true or you will experience querying inconsistencies in dev mode. Note that this will severely decrease performance in dev mode only. invoke mongoid remove app/models/model_name.rb invoke test_unit remove test/unit/model_name_test.rb remove test/fixtures/model_names.yml
あとデフォルトでtimestampを使えるみたいなのでそっちも使ってみる。
% rails generate model model_name --timestamps=true Mongoid config not found. Create a config file at: config/mongoid.yml to generate one run: rails generate mongoid:config Mongoid preload_models is set to false. If you are using inheritance in your application model please set this to true or you will experience querying inconsistencies in dev mode. Note that this will severely decrease performance in dev mode only. invoke mongoid create app/models/model_name.rb invoke test_unit create test/unit/model_name_test.rb create test/fixtures/model_names.yml
timestamp付きのモデルを確認。
%vim app/models/model_name.rb class ModelName include Mongoid::Document include Mongoid::Timestamps end
とりあえず今日はこれだけ。
ログを見てると"config/mongoid.ymlがないからrails generate mongoid:configしろ!"って書いてあるので後でしておく。