Ruby On Rails Lesson
The Basic Model
The Micropost model needs only two attributes: a content attribute to hold the micropost’s content,2 and a user_id to associate a micropost with a particular user. As with the case of the User model (Listing 6.1), we generate it using generate model
This produces a migration to create a microposts table in the database (Listing 10.1); compare it to the analogous migration for the users table from Listing 6.2.
Note that, since we expect to retrieve all the microposts associated with a given user id in reverse order of creation, Listing 10.1 adds an index (Box 6.2) on the user_id and created_at columns:
By including both the user_id and created_at columns as an array, we arrange for Rails to create a multiple key index, which means that Active Record uses both keys at the same time. Note also the t.timestamps line, which (as mentioned in Section 6.1.1) adds the magic created_at and updated_at columns. We’ll put the created_at column to work in Section 10.1.4 and Section 10.2.1.
We’ll start with some minimal tests for the Micropost model based on the analogous tests for the User model (Listing 6.8). In particular, we verify that a micropost object responds to the content and user_id attributes, as shown in Listing 10.2.