#238 Mongoid
Mongoid is a polished, high-level Ruby gem for accessing MongoDB. Here I cover installation, adding fields, validations, associations, and keys.
- Download:
- source codeProject Files in Zip (109 KB)
- mp4Full Size H.264 Video (18.2 MB)
- m4vSmaller H.264 Video (12.1 MB)
- webmFull Size VP8 Video (28.3 MB)
- ogvFull Size Theora Video (22.7 MB)
There is a newer version of this episode, see the revised episode.
Resources
bash
bundle rails g mongoid:config rails g scaffold article name:string content:text rails g model comment name:string content:text rails g controller comments rails g scaffold author name:string
Gemfile
gem 'mongoid', '2.0.0.beta.19' gem 'bson_ext'
models/article.rb
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
models/comment.rb
class Comment include Mongoid::Document field :name field :content embedded_in :article, :inverse_of => :comments end
models/author.rb
class Author include Mongoid::Document field :name key :name references_many :articles end
comments_controller.rb
def create @article = Article.find(params[:article_id]) @comment = @article.comments.create!(params[:comment]) redirect_to @article, :notice => "Comment created!" end
articles/_form.html.erb
<div class="field"> <%= f.label :published_on %><br /> <%= f.date_select :published_on %> </div> <div class="field"> <%= f.label :author_id %><br /> <%= f.collection_select :author_id, Author.all, :id, :name %> </div>
articles/show.html.erb
<% if @article.comments.size > 0 %> <h2>Comments</h2> <% for comment in @article.comments %> <h3><%= comment.name %></h3> <p><%= comment.content %></p> <% end %> <% end %> <h2>New Comment</h2> <%= form_for [@article, Comment.new] do |f| %> <p><%= f.label :name %> <%= f.text_field :name %></p> <p><%= f.text_area :content, :rows => 10 %></p> <p><%= f.submit %></p> <% end %>