Phoenix Web Development
上QQ阅读APP看书,第一时间看更新

Storing and Retrieving Vote Data with Ecto Pages

When we left off last, we had sat down and gained a thorough knowledge of controllers and the entire connection model. We began with the internal request, going through the router, hitting the glue of the controller, and finally wiring up data and displaying it back to the user via our views and templates. All of this is great by itself, but if we don't have somewhere to store and retrieve data, our application is largely decorative and not terribly functional. We're going to change that by implementing a means of getting our data and putting it back into a database.

Before we can dive too far into storing our data, however, we need to understand the model behind how Ecto takes the information from the database and presents it to the application at large. Ecto, the database library that we'll be using in our project, relies on the concepts of Schemas and Contexts. Through the combination of these techniques, we can safely separate out the side effects of working with a database that may be changing constantly due to interactions with our application. Let's take a few minutes first, however, to understand how contexts and schemas interact with each other and what roles they take in the data interaction layer of our application.

In this chapter, we'll take a deep dive into the topics most directly facing the backend of our application. Specifically, we'll be taking on:

  • What the roles of schemas are in our application
  • Creating new migrations
  • How to write migrations
  • Understanding the roles of contexts
  • Hooking a context up to a controller
  • Writing some basic unit tests to cover functionality

These are all necessary to really understand how the database side of things glues the rest of our application together over time. By the end of the chapter, you should have a thorough working knowledge of all of the database-specific parts of your application and how they all fit together!