Rails and Model Relationships
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
Test the BlogDemo Project
- Open the BlogDemo project.
- Run the project and browse to http://localhost:3000/blog to verify it works.
Create the Comment Model
- Switch back to the Projects tab, right-click the Models folder and generate a new model named Comment.
- Open 003_create_comments.rb and add post_id, created_at and comment columns to the up method as follows:
- Right-click the BlogDemo project and select Migrate Database > To Current Version
Define the Model Relationships
- Add the has_many association to post.rb:
- 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:
- Delete blog_controller.rb
- Generate Scaffold. Set the Model Name to Post and the Controller Name to Blog.
- 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.
- Modify the show action to save the post id to the flash:
- Create the following post_comment action:
Modify the View to Post Comments
- Open show.rhtml and add the following to the bottom:
- 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.
- Add a post_comments instance variable to the show action to collect the comments:
- Add the following to show.rhtml to display the comments. The <hr> and <h4>Comments</h4> already exist and are provided for placement reference.
- Add another comment: