LoginSignup
36

More than 5 years have passed since last update.

Ruby On Rails で MongoDBを使ってみるよ

Last updated at Posted at 2014-06-13

ネットで探すといろいろやり方あるのですが、各アプリケーションのバージョンによってやり方が微妙に違うようなのでバージョンはよく確認しましょう。
今回は

  • Ruby 2.0.0
  • Ruby On Rails 4.1.1
  • MongoDB 2.6.1

です。

各アプリはインストールされている前提です。

プロジェクト作成

railsプロジェクトはActiveRecordなしで作成します。

$ rails new sample --skip-active-record

mongoidをインストール

GemFileに以下を追加します。

gem 'io-console'
gem 'mongoid', '4.0.0.beta1'

バージョン指定は特にしなくても動くと思うのですが、、、とりあえずこれで動いてますということで。。。

mongoidインストール後

$ rails g mongoid:config

を実行します。
するとsample/config/mongoid.ymlファイルが作成されます。

デフォルトでrails newで作成した名前が入っているので、必要に応じてここでデータベース名を指定します。

モデル作成してMongoDBを操作

モデル作成
rails g model example

登録

登録
example = Example.new(:hogehoge => 'hogehoge', :fugafuga=>'fugafuga')
example.save

検索

検索
example = Example.where(:hogehoge => 'hogehoge')

この辺はRDB使う場合とほぼ同じ
mongodbはスキーマレスなんで最初にテーブル作成とかいらないのでいいですね。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36