Chapter 16 - Blog comments with Ajax

Introduction

In this chapter, we extend the RailsSpace blog engine by allowing users to comment on blog posts. After all our hard work on RESTful blogs and posts in Chapter 15, comments by themselves are relatively straightforward, so we'll keep things interesting by using Ajax to implement them. Since our comments are RESTful as well, we'll have a chance to see how nicely REST and Ajax play together.

Although there are plenty of useful new techniques in this chapter, including several Rails Ajax helpers and the remarkable Ruby JavaScript (RJS), we should note that there is a layer of code that we will not explain. We will peek under the hood to see some of the code that produces the Ajax effects, but ultimately the actual implementation—written in JavaScript using a couple of slick JavaScript libraries—will remain mysterious. Some of the libraries we'll be using are fabulous, miraculous, and, even, ahem, "scriptaculous," and we bow to the JavaScript gods behind these tools.

Table of Contents

  • 16.1 RESTful comments 479
    • 16.1.1 Comments resource 480
    • 16.1.2 Comment model and associations 481
    • 16.1.3 The Comments controller and a preemptive partial 482
    • 16.1.4 Routing comments 484
  • 16.2 Beginning Ajax 485
    • 16.2.1 New comments 486
    • 16.2.2 Comment creation 490
    • 16.2.3 Destroying comments 492
  • 16.3 Visual effects 495
    • 16.3.1 RJS files and the first effect 495
    • 16.3.2 Two more effects 497
    • 16.3.3 A cancel button 499
    • 16.3.4 Degrading gracefully 499
  • 16.4 Debugging and testing 501
    • 16.4.1 Another look at new 502
    • 16.4.2 Testing Ajax with xhr 502

Source Code

Errata

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

  1. p. 480. The code output should have "db/migrate/011_create_comments.rb"
  2. p. 480. Listing 16.1 should be titled db/migrate/011_create_comments.rb
  3. p. 483. Listing 16.5 There should be a vertical ellipsis ... before private
  4. p. 486. The reference in the second paragraph to Section 6.2.2 should be 6.2.3.
  5. p. 503. In Listing 16.28, change
    fixtures :comments, :posts, :blogs, :users, :specs
    to
    fixtures :comments, :posts, :blogs, :users, :specs, :geo_data