Create relationships when scaffolding Create relationships when scaffolding ruby-on-rails ruby-on-rails

Create relationships when scaffolding


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.


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


You can also use belongs_to like this:

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