Chapter 11. Associating records and accepting bids
This chapter covers
- Allowing users to bid on items
- Defining Ecto associations between items, bids, and users
- Using Ecto to load associated schemas
- Preloading associations to avoid N+1 queries
In the past few chapters, we’ve discussed using Ecto to define schemas for users and items. You can create new auction items, register a user, and log in and out as a user. There are a couple of things missing, though:
- There’s no way for a user to bid on an item.
- Items aren’t owned by anyone. In fact, a random stranger could create new auction items on your site right now.
Both of these points are similar in that they rely on associating one record or schema with another. Bids (which don’t yet exist) should belong to a user and an item. When you create new items, you want an item to be owned by a user, and a user can own many items. Both a user and an item can have many bids.
This chapter covers Ecto associations. You’ll explore them in this chapter by creating bids and allowing a user to bid on an item, creating associations between the three. Figure 11.1 illustrates these associations. Each dotted arrow indicates that one type has many of the other it’s pointing to. Likewise, each solid arrow represents a type that belongs to the type it’s pointing to.