Time for action — modeling the Order class

Now, let's look at a few new aspects! An order is of two types; either a lease or a purchase. The Order model can be written as follows:

# app/models/order.rb
class Order
include Mongoid::Document
field :created_at, type: DateTime
field :type, type: String # Lease, Purchase
belongs_to :book
belongs_to :member
embeds_one :lease
embeds_one :purchase
end

The Purchase model can be written as follows:

# app/models/purchase.rb
class Purchase
include Mongoid::Document
field :quantity, type: Integer
field :price, type: Float
embedded_in :order
end

The Lease model can be written as follows:

# app/models/lease.rb
class Lease
include Mongoid::Document
field :from, type: DateTime
field :till, type: DateTime
embedded_in :order
end

What just happened?

Here we are following the standard paradigm for a type field. If the type is :lease, we shall look up the Lease embedded object. If it's :purchase, we shall look up the Purchase embedded object. We could have made this polymorphic, but then how will we learn the different ways of coding?

Understanding Rails routes

What are routes, did you say? They are the URLs that we shall use to access the application from the web browser. Rails goes one step further and sets up RESTful routes by default.

Note

REST stands for REpresentational State Transfer. It represents resources and actions performed on them. Given a combination of the resource, HTTP verbs (GET, PUT, POST and DELETE) and some basic actions, we can define standard operations.

What is the RESTful interface?

RESTful interfaces are the definition of resources from which the URLs are generated. We can understand this better from the following table:

HTTP Verb

Author Resource URL

Controller Action

Description

GET

/authors

:index

List all Authors

GET

/authors/:id

:show

Show Author details

GET

/authors/:id/edit

:edit

Show the edit Author form

PUT

/authors/:id

:update

Update Author

POST

/authors

:create

Create Author

GET

/authors/new

:new

Show the new author form

DELETE

/authors/:id

:destroy

Delete an Author

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

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