Time for action — changing models

Let's take a look at the Book model:

class Book
include Mongoid::Document
field :title, type: String
field :publisher, type: String
end

If we have such a model, what does the object look like? Execute the following command to find out:

irb> Book.create(publisher: "Dover")
=> #<Book _id: 4f216427fed0eb86ac000001, _type: nil, title: nil, publisher: "Dover">

Now, suppose we wanted to add a few fields to the Book model, how do we do that? Change the code! The code would now look like the following:

class Book
include Mongoid::Document
field :title, type: String
field :publisher, type: String
field :published_on, type: Date
end

What just happened?

Now, let's see what happens when we create a new object as well as access the earlier one we created. Execute the following commands:

irb> Book.create(publisher: "Packt", published_on: Date.today)
=> #<Book _id: 4f21660cfed0eb86ac000002, _type: nil, title: nil, publisher: "Packt", published_on: 2012-01-26 00:00:00 UTC>

So far, so good! But what happens to the earlier object created?

irb> Book.where(publisher: "Dover").first
=> #<Book _id: 4f216427fed0eb86ac000001, _type: nil, title: nil, publisher: "Dover", published_on: nil>

Notice the published_on field that is nil!

Tip

Always try to avoid removing fields — it can cause undue trouble.

So, go forth and change the models to your heart's content! No worries.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.136.249