How to model a one-to-many relationship in rails

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.

Scaffold Comments

rails generate scaffold Comment post_id:integer body:text

Next you need to setup the mysql table for comments

rake db:migrate

After you have this complete, you need to modify the comment model found under app/model

belongs_to :post

Next you need to modify the post model object found under app/model

has_many :comments

Alter your views to reflect this new relationship

Add the following to your show.html.erb template found under app/views/posts

comments markup show

Now in your comments controller modify the create method found under app/controllers

comments controller

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

blog routes

now fire up the web server and try to add a comment

rails server

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