Databases Reference
In-Depth Information
db["forms"].save comment_form
Each time we want to render a page with the comment form, we can query for the form
document by its name:
db["forms"].find_one :_id => "comments"
The single document returned contains all the information we need in order to render
the form, including the name, label, and type for each input field that needs to be
rendered. When a form needs to be changed, editors can easily add a field or specify
additional constraints for an existing field.
When we get a user submission for a form, we can run the same query as earlier to get
the relevant form document. We'll need this in order to validate that the user's sub-
mission includes values for all required fields and meets any other requirements speci-
fied in our form. After validation, we can save the submission as a separate document
in a submissions collection. A submission for our comment form might look like this:
comment_submission = {
:form_id => "comments",
:name => "Mike D.",
:email => "mike@example.com",
:comment => "MongoDB is flexible!"
}
We're again leveraging the document model by including custom keys for each sub-
mission (here we use :name , :email , and :comment ). The only key that we require in each
submission is :form_id . This allows us to efficiently retrieve all submissions for a certain
form:
db["submissions"].find :form_id => "comments"
To perform this query, we should have an index on :form_id :
db["submissions"].create_index :form_id
We can also use :form_id to retrieve the form document for a given submission.
Ruby Object Mappers and Using MongoDB with Rails
There are several libraries written on top of the basic Ruby driver to provide things like
models, validations, and associations for MongoDB documents. The most popular of
these tools seem to be MongoMapper and Mongoid . If you're used to working with
tools like ActiveRecord or DataMapper, you might consider using one of these object
mappers in addition to the basic Ruby driver.
MongoDB also works nicely with Ruby on Rails, especially when working with one of
the previously mentioned mappers. There are up-to-date instructions on integrating
MongoDB with Rails on the MongoDB site .
 
Search WWH ::




Custom Search