Chapter 14 - Friendships

Introduction

With the double-blind email system in place, we suppose that RailsSpace is now technically a social network, but most real-world social networks worthy of the name give users a way to select preferred members. Following tradition, we call such distinguished users friends. Adding friends to RailsSpace is the goal of this chapter.

Friendships represent the most challenging data modeling problem we've encountered so far. To solve it, we'll have to learn about simulated table names, foreign keys, and the has_many database association. Adding and managing friendships will then take place through both email and web interfaces. By the end of the chapter, we'll be in a position to put a list of friends on the hub and user profile, making use of the avatar thumbnails from Chapter 12.

Table of Contents

  • 14.1 Modeling friendships 411
    • 14.1.1 Friendships in the abstract 412
    • 14.1.2 Friendship model 413
    • 14.1.3 Creating pending friendships 415
    • 14.1.4 Friendship request 416
    • 14.1.5 Completing the Friendship model 417
    • 14.1.6 Testing the Friendship model 419
  • 14.2 Friendship requests 420
    • 14.2.1 Friendship request link 420
    • 14.2.2 Controlling the request 423
  • 14.3 Managing friendships 426
    • 14.3.1 has_many :through 426
    • 14.3.2 Hub friendships 428
    • 14.3.3 Friendship actions 431
    • 14.3.4 Testing friendship requests 433

Source Code

Errata

As of the first printing, these are the known corrections:

  1. p.419. Listing 14.5 should be test/unit/friendship_test.rb instead of test/units/friendship_test.rb.
  2. p. 430. Add the following validition to the User model to avoid overwriting the default avatar images:
      def validate
        # Protect against overwriting default thumbnail...
        if %w(default_thumbnail default).include?(screen_name)
          errors.add(:screen_name, "cannot be that, nice try though")
        end
      end