Chapter 10 - Community

Introduction

Giving users the ability to create and edit profiles is a good start, but for RailsSpace to be useful to its members, we need to have ways for them to find each other. In this chapter and the next, we develop three methods for finding users.

  1. A simple index by name.
  2. Browsing by age, sex, and location.
  3. Full-text searches through all user information, including specs and FAQs.

In this chapter, we'll populate the RailsSpace development database with sample users so that our various attempts to find users will not be in vain. Then we'll develop an alphabetical community index to list RailsSpace members in the simplest way possible. Though straightforward, the community index will introduce several new aspects of Rails, including results pagination and a demonstration of the find function's remarkable versatility.

Data

We mirror the YAML files from the Caltech Alumni system here:

Table of Contents

  • 10.1 Building a community (controller) 303
  • 10.2 Setting up sample users 304
    • 10.2.1 Collecting the data 305
    • 10.2.2 Loading the data 305
  • 10.3 The community index 308
    • 10.3.1 find’s new trick 309
    • 10.3.2 The index action 311
    • 10.3.3 The alphabetical index 313
    • 10.3.4 Displaying index results 316
  • 10.4 Polishing results 320
    • 10.4.1 Adding pagination 321
    • 10.4.2 A results summary 323

Source Code

Errata

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

  1. p. 312. Listing 10.4 is titled app/views/controllers/community_controller.rb but but should be app/controllers/community_controller.rb
  2. p. 317. A reference to app/view/profile/show.rhtml should be app/views/profile/show.rhtml
  3. p. 318. There's a logic error in the calculation of the user's age in the spec model. Listing 10.11, which appears as
      # Return the age using the birthdate.
      def age
        return if birthdate.nil?
        today = Date.today
        if today.month >= birthdate.month and today.day >= birthdate.day
          # Birthday has happened already this year.
          today.year - birthdate.year
        else
          today.year - birthdate.year - 1
        end
      end
    should instead be
      # Return the age using the birthdate.
      def age
        return if birthdate.nil?
        today = Date.today
        if (today.month > birthdate.month) or 
           (today.month == birthdate.month and today.day >= birthdate.day)
          # Birthday has happened already this year.
          today.year - birthdate.year
        else
          today.year - birthdate.year - 1
        end
      end