MongoDB x ROR on EC2
Summary
MongoDBを利用したwebアプリを作ってみた。
MongoMpperとMongoidはどちらもODM(Object Document Mapper)なはずだけど、MongoidはMongoMapperがないと動かなかった。configファイルの初期化でこける。
How To
mkdir rails cd rails rails new mongo_test --skip-active-record cd mongo_test/
vi Gemfile
gem 'mongo_mapper' gem 'bson_ext' gem 'mongoid' # add belows for avoiding error gem 'execjs' gem 'therubyracer'
bundle install
vi config/initializers/mongo.rb
# coding: utf-8 MongoMapper.connection = Mongo::Connection.new('localhost', 27017) MongoMapper.database = "#mongo_test-#{Rails.env}" # if defined?(PhusionPassenger) PhusionPassenger.on_event(:starting_worker_process) do |forked| MongoMapper.connection.connect if forked end end
mongoid の 設定ファイルを初期化する
rails g mongoid:config ls config/mongoid.yml
scaffold
rails g scaffold Post title:string subscription:text
server 起動
rails s
ブラウザから確認・データ登録
http://${public_dns}:3000 http://${public_dns}:3000/posts
登録した内容を確認
mongo use mongo_test_development show collections db.posts.find()
reference
webアプリサンプル 他
- 時間がある時にやってみたい
- 本家サイトのGettingStarted. これは MongoMapperのみ
- http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-ruby-on-rails-3/
- 簡単なブログアプリ
疑問
- filedの定義が自由にするには、どんなModelにすればいいんだ?クラス変数決めた時点で、そのModelはfiled固定になっちゃうじゃん。ひとつのModelをextendsしてフィールド足してく?...それで同じcollectionに格納するとか?でも、それって大して柔軟でもないよね。
気になるところ
- Mongoid で動的にフィールドが追加できるっぽい
- http://mongoid.org/en/mongoid/docs/documents.html#dynamic_fields