Skip to main content

Rails and Model Relationships

Posted by bleonard on April 27, 2007 at 5:33 PM PDT

Here we enhance our Ruby web log so that readers can add comments. In the process we will learn how to deal with model relationships in Rails, as a single post can have zero or more comments.

Setting Things Up

I'm going to begin from where I left off in my previous post: Rails and Database Migrations. Alternatively, you can start from BlogDemo.zip, which is the completed project from that post.

Test the BlogDemo Project

  1. Open the BlogDemo project.
  2. Run the project and browse to http://localhost:3000/blog to verify it works.

Create the Comment Model

  1. Switch back to the Projects tab, right-click the Models folder and generate a new model named Comment.


  2. Open 003_create_comments.rb and add post_id, created_at and comment columns to the up method as follows:






  3. Right-click the BlogDemo project and select Migrate Database > To Current Version



Define the Model Relationships

  1. Add the has_many association to post.rb:




  2. Add the belongs_to association to comment.rb:



Regenerate our Controller Scaffolding

When we first created this project and generated the scaffolding for the Post model, we didn't choose to overwrite the existing blog controller, so the scaffolding actions were not created. So that we can customize the scaffold actions, we will delete the blog_controller.rb and generate the scaffolding again. Note, we are choosing not to use the overwrite option because our views have been customized and we we don't want to loose those customizations:

  1. Delete blog_controller.rb
  2. Generate Scaffold. Set the Model Name to Post and the Controller Name to Blog.
  3. Open the newly created blog_controller.rb, which now has all of the scaffold actions (index, list, show, new, create, edit, update and destroy).

Create a New Action for Posting Comments

We're going to modify the show view to include a text area so comments can be added. First we're going to create a new action for posting the comments.

  1. Modify the show action to save the post id to the flash:






  2. Create the following post_comment action:




Modify the View to Post Comments

  1. Open show.rhtml and add the following to the bottom:



Test

  1. In the browser, click one of the Permalinks to view an entry's details. Test adding a comment:







Displaying the Comments

Our blog doesn't yet display the comments that have been added, let's fix that.

  1. Add a post_comments instance variable to the show action to collect the comments:






  2. Add the following to show.rhtml to display the comments. The <hr> and <h4>Comments</h4> already exist and are provided for placement reference.



Test

  1. Add another comment:



 

The Completed Application

BlogDemoComments.zip






Related Topics >>