First and foremost, we need to ensure that we have our development environment set up. It's common to use multiple versions of Ruby for development; I use RVM to manage these versions. As we can have multiple versions of the same gem installed on our machines, we use RVM gemsets to manage the gems we need for our work.
To check the Ruby version, check the version that is installed using the following command:
Note
Ruby 2.1 is due to be released in December, 2013. Everything in this book will be fully compatible with Ruby 2.1 too.
We are currently using MongoDB v2.4.6—verify that, using the following command:
If you don't see this, it's quite likely that you have not installed MongoDB or it isn't running. Get going!
First and foremost, let's install the Rails gem.
This installs Rails 4.0.0.
Note
At the time of writing this book, the Rails version was 4.0.0. All commands would be fully compatible with the latest Rails version.
Now, let's create the Sodibee project.
This creates a new Rails project. The –O
option tells Rails to skip ActiveRecord (we don't need it), and –T
tells Rails to skip test unit. (We plan to use rspec
later).
Tip
When you run the preceding command, it initiates a bundle install and updates our bundle with the default gems. If you are as impatient as I am, you may interrupt the process and press Ctrl + C to stop it, as we need to modify Gemfile
to add other gems anyway.
Now, open Gemfile
and configure for Mongoid.
Note
Mongoid master is currently in sync with Rails 4. So, if we install using the released gem, it will install Version 3.x.
We're almost done. Issue the following command to update the bundle with our Mongoid gem:
If you did not use the –O
option, you can run the following instructions to remove ActiveRecord from the application as we don't need it. Check and remove database.yml
under config
, if it has been generated. Next ensure that application.rb
under config
has the following lines:
Tip
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Notice that there is no require "rails/all"
. This ensures that the ActiveRecord
railtie is not loaded. However, sometimes this causes a conflict with the environment settings. So, in case you face a problem starting the Rails console, remove the following line from development.rb
under config/environments
(and as required from the other environment files):
This should get us going. Now issue the following command to set up Mongoid:
This generates mongoid.yml
under config
.
Test this basic Rails setup by starting the console.
If you see the preceding command prompt, we are set.
Now that we have our environment set up, let's create our basic models. In the Author
model, we shall now add a field called name
, and create a relation between the Author
model and the Address
model.
Now, let's create the Address
model with a number of fields and relations.
Now, let's test the code that we have written.
Note
Did you notice that we are not using the hash rocket (=>) notation for defining the hash of options for the field
method? Instead of :type => String
, we are using the JSON notation instead. We shall follow this standard throughout the book.
Now that we have created the models, let's test it out quickly:
As we can see, this creates an Author
object and its corresponding Address
object. Mongoid includes ActiveModel and you may notice the similarity in these methods if you have used ActiveRecord.
Tip
We have used create_address
because an author has only one embedded address. If, an author had multiple addresses, we would have used a.addresses.create
.
Here, we have double-checked that the author is indeed persisted to the database. Since this is MongoDB, we can dynamically add attributes to the object!
So, let's see what happened in Mongoid and MongoDB. First, let's see what is in the log file development.log
under log
.
When we issued the command Author.create(name: "Charles Dickens")
, it generated the following output:
Now, when we issued the second command a.create_address(street: "Picadilly Circus", city: "London", country: "UK")
, it updated the Author
object, and created an embedded Address
document as seen in the following line:
Now that we have seen what INSERT
and UPDATE
look like, querying the Author collection with Author.first
generates the following result:
And since we want to query the address, we look it up using Author.first.address
. This generates the following line:
Now there's something interesting about the preceding output—the last two commands on the Author
model fired the same query, and look at the difference in the query result! The same query is fired because the address is an embedded document. So, to fetch the address of an author, you fetch the Author
object itself. The difference of 66 ms and 0.5 ms in the query response is because for the first lookup MongoDB loads the document from the disk and puts it into its memory-mapped file. The second time, the document is simply looked up in cache (the memory-mapped file) and hence the lookup is faster.
When we issued the command a['language'] = "English"
, and saved the object using a.save
; this is what we see:
This is the result of dynamic attribute update. Even though we did not specify language
as a field in the Author
model, we can set it as an attribute for the Author
object. Did you notice that the update for dynamic attributes is no different from the standard update query in MongoDB?
However, there is a difference when accessing it in Mongoid. The Author.first.language
parameter may throw an error sometimes, but Author.first[:language]
will always succeed. Let's see an example:
Here we have created a new Author
object. However, when we try to update the object using the dot notation a.language
, it gives an error. As we can see in the following command lines, method_missing
does not dynamically create the accessor method if the dynamic attribute does not already exist.
Now, if we try to update the dynamic attribute without using the dot notation, it works!
Since we have saved it now, when we access the dynamic attribute language
again, method_missing
creates the accessor method because the dynamic attribute exists. So, now even the dot notation works.
Origin is a gem that provides the DSL for Mongoid queries. Though at first glance, a question may seem to arise as to why we need a DSL for Mongoid queries; If we are finally going to convert the query to a MongoDB-compliant hash, then why do we need a DSL?
Origin was extracted from Mongoid gem and put into a new gem, so that there is a standard for querying. It has no dependency on any other gem and is a standalone pure query builder. The idea was that this could be a generic DSL that can be used even without Mongoid!
So, now we have a very generic and standard querying pattern. For example, in Mongoid 2.x we had the criteria any_in
and any_of
, and no direct support for the and
, or
, and nor
operations. In Mongoid 2.x, the only way we could fire a $or
or a $and
query was like this:
And now in Mongoid 3, we have a cleaner approach.
Origin also provides good selectors directly in our models. So, this is now much more readable:
As we shall see later in the book, Origin has a lot more cool features.