rails3.2とmongodb
環境整備
プロジェクト作成
rails new mongotest -O
- OオプションでActiveRecordを省略
Gemfileに以下を追記
gem 'therubyracer' gem 'mongoid'
bundle install
mongoidの設定ファイル作成
rails g mongoid:config
config/mongoid.ymlが作成される
モデル
artists.rb
class Artist include Mongoid::Document field :name, type:String end
コントローラー
artists_controller.rb
class ArtistsController < ApplicationController def index @artists = Artist.all end def create @artist = Artist.create!(params[:artist]) redirect_to :index end def new @artist = Artist.find(params[:id) end
ビュー
index.html.erb
<%= link_to 'new artist', :action=>'new' %> <br /> <% @artists.each do |artist| %> <p> <%= artist.name %> <%= link_to 'show', artist %> </p> <% end %>
new.html.erb
<h1>new</h1> <%= form_for @artist do |f| %> <%= f.text_field :name %> <%= f.submit '登録' %> <% end %>
show.html.erb
<%= @artist.name %>
mongodb操作
コンソールでの操作
use データベース名 db.テーブル名.find()
詳細はhelpコマンドで確認
出来上がったプロジェクト in github
https://github.com/windows11/mongotest