Chapter 3 - Modeling users
Introduction
Having a front page up and running is a good start, but now it's time to get to the core of any social networking site: a database of registered users. In the process, we'll experience the remarkable power of models—the M in MVC—which, perhaps more than anything else, sets Rails apart from other frameworks.The purpose of this chapter is to build a User model to represent RailsSpace users, deciding which attributes (such as screen names, email addresses, etc.) we want them to have. The User model will rely on Active Record, a library for communicating between Ruby objects and relational databases. We'll spend much of the chapter exploring Active Record using the console, which is essentially a command line for Rails. We'll also learn about migrations, which provide a convenient and flexible way to manage our data models using pure Ruby.
Table of Contents
- 3.1 Creating the User model 43
- 3.1.1 Setting up the database 43
- 3.1.2 Migrations and the User model 46
- 3.1.3 The first user migration 47
- 3.1.4 Raking the migration 49
- 3.2 User model validations 51
- 3.2.1 The console 52
- 3.2.2 A simple validation 54
- 3.2.3 Validations in action 56
- 3.2.4 Improving validations 57
- 3.2.5 Full-strength validations 59
- 3.2.6 Magic columns 61
- 3.3 Further steps to ensure data integrity (?) 63
Source Code
- Listing 3.1 config/database.yml
- Listing 3.2 db/migrate/001 create users.rb
- Listing 3.3 db/migrate/001_create_users.rb
- Listing 3.4 app/models/user.rb
- Listing 3.5 app/models/user.rb
- Listing 3.6 app/models/user.rb
- Listing 3.7 app/models/user.rb
- Listing 3.8 app/models/user.rb
- Listing 3.9 app/models/user.rb
- Listing 3.10 db/migrate/002_add_user_timestamps.rb
Errata
As of the first printing, these are the known corrections:
- p. 48. The references to Section 4.2.3 should instead be to Section 4.2.2.
- p. 54. refl ecting should be reflecting