Setting up a forum is a great way to keep your customers interested and get feedback on what you're doing. This article, the first part of a four-part series, will show you how to set one up for an online bookstore using Ruby on Rails. It is excerpted from chapter six of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Forum Implementation - Using the Threaded Forum Plugin (Page 2 of 4 )
The acts_as_threaded plugin was originally developed by Bob Silva and allows you to easily implement a forum. As you've seen in previous chapters, plugins are used by developers to extend the core functionality provided by the Ruby on Rails framework. Implementing a forum with the acts_as_threaded plugin is as simple as most tasks in Rails. Install the plugin, and then add a database table, model, controller, and view.
The complex logic for storing forum data in a relational database, like MySQL, is handled by the plugin, allowing you to concentrate on implementing the forum, instead of writing infrastructure code. By not reinventing the wheel, you can implement the forum faster and probably with fewer bugs than if you implemented it yourself, which means a happier client in the end.
Download the plugin installation package from www.railtie.net/plugins/acts_as_threaded.zip. Then extract the package to the vendor/plugins directory, which, in our case, is /home/george/projects/emporium/vendor/plugins. Lastly, verify that you have the following files in the vendor/plugins/acts_as_threaded directory:
The init.rb file is called by Rails on startup and initializes the plugin. The threaded.rb file contains the actual plugin code, which we will use to implement the forum.
Activating the plugin is as simple as adding a call to the acts_as_threaded method to your model, as in this example:
class Post < ActiveRecord::Base acts_as_threaded end
The acts_as_threaded plugin adds the instance methods listed in Table 6-1 to the model.
Table 6-1. Instance Methods Added by the acts_as_threaded Plugin
Returns true if the post is the root post in the thread
Returns true if the post is the child of another post
Adds a reply to the post
Returns the number of replies under this post
Returns an array containing the post itself and all replies under it
Returns an array containing all replies
Returns an array containing only replies to this post
We can hear George swearing loudly in the basement, "Damn sewer rat, you never learn! Do you? This is your last... ." Then we hear a gun of some sort being fired six times. "Was that a Smith & Wesson? we ask ourselves, before continuing with the forum implementation.