Published on September 10, 2010 by Toran Billups
Finishing the simple blog implementation does require a one-to-many relationship between posts and comments. So first we need to add the comment object and scaffold out the view/migration/etc.
rails generate scaffold Comment post_id:integer body:text
Next you need to setup the mysql table for comments
After you have this complete, you need to modify the comment model found under app/model
Next you need to modify the post model object found under app/model
Add the following to your show.html.erb template found under app/views/posts
Now in your comments controller modify the create method found under app/controllers
Also add this to the post controller show method to ensure we have a collection of comments for each post to show
@comments = @post.comments
And finally alter your routes file to look like the below found under config/routes.rb
now fire up the web server and try to add a comment
You should now have a working blog with both a many-to-many and now a one-to-many relationship!
If you want the source for the finished blog application you can download it here