42

Hi I am new to Ruby on Rails. I am trying to create a small blog site. I have two tables Posts and Comments. Each Post will have many comments. I generate the tables using these commands.

rails g scaffold Post title:string body:text author:string
rails g scaffold Comment body:string author:string

Now I want to add the relationship to the model classes. I add has_many :comments to the Post class and belongs_to :post to the Comment class. However when I try to call post.comments I get a runtime error saying SQLException: no such column: comments.post_id. Should I create a migration and add post_id under Comment or is there a way to achieve this when scaffolding?

André Willik Valenti
  • 1,702
  • 14
  • 21
Stefan Bossbaly
  • 6,682
  • 9
  • 53
  • 82

3 Answers3

156

Scaffold actually provides a way to generate relationships, you should use the :references data type

rails g scaffold Comment body:string author:string post:references

This will generate a migration for the comments table with a post_id field and index for it. The generator will also add belongs_to :post to the Comment model.

It will not however generate the reverse side of the relationship so you'll need to add

has_many :comments

to the Post model yourself. You will also need to add nested resource routing if this is something you need as the generator can not handle this.

JamieD
  • 2,707
  • 2
  • 20
  • 19
  • 1
    When you manually add the has_many field how do you generate the migration? – lapinkoira Apr 11 '16 at 12:08
  • 3
    @lapinkoira In the above example, the `post:references` bit that's included when scaffolding the Comments model will add a foreign key on a Comment referencing the Post that it belongs to. The `has_many :comments` relationship needs to be added to the Post model but doesn't require an additional migration. – darkmoves May 30 '16 at 15:57
9

You are definitely on the right track. If you add the post_id column when generating the Comment scaffold your relationship will then work (although you still need to add the has_many :comments and belongs_to :post)

So the updated generator call would look like this:

rails g scaffold Comment body:string author:string post_id:integer
agmin
  • 8,948
  • 2
  • 21
  • 27
3

You can also use belongs_to like this:

rails g scaffold Comment body:string author:string post:belongs_to
Jeremy Lynch
  • 6,780
  • 3
  • 52
  • 63