In this third part of a four-part series on setting up a forum for an online bookstore using Ruby on Rails, we pick up where we left off; we'll also start setting up the sections that allow visitors to view forum posts. This article is excerpted from chapter six of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Forum Implementation: Viewing Posts (Page 1 of 4 )
Completing the Controller
The controller contains two actions that are used in the Post to Forum user story. One displays the form, and the other takes the user input and persists the post to the database. Both the post and create actions exist already, but they contain no code, so modify app/controllers/forum_controller.rb as follows:
def post @page_title = 'Post to forum' @post = ForumPost.new end
def create @post = ForumPost.new(params[:post]) if @post.save flash[:notice] = 'Post was successfully created.' redirect_to :action => 'index' else @page_title = 'Post to forum' render :action => 'post' end end
The post action does one thing: it creates a new ForumPost object that is used by the form tags in the view. The create action is a bit more complex. It receives the form input from the user and creates a new ForumPost object. It then tries to save it to the database. If the user-supplied data passes validation, it redirects the user to the forum main page. If there are any validation errors, it renders the create post page instead, where we use the error_messages_for helper to show the validation errors to the user.
Creating the View
Recall that the Post to Forum user story is implemented with the controller's post action, which directly maps to the app/views/forum/post.rhtml view. The ERB code for this view is shown in Listing 6-4. Save the code in app/views/forum/post.rhtml .
Listing 6-4. View for the Post to Forum User Story
The view uses the built-in Ruby on Rails form helpers hidden_field , text_field , and text_area for creating the form fields. Note that we are using label tags and that the label tags for attribute is used to associate the label with a form field. Using label tags in forms is important because it improves usability, such as by extending the clickable area to outside the field. The hidden field in the view is used by the Reply to Post user story, which we will implement later in this chapter.