Skip to content

Instantly share code, notes, and snippets.

@jhonnatas
Last active January 26, 2019 01:53
Show Gist options
  • Save jhonnatas/46461dcdad3ef87477362f7351bbc5ad to your computer and use it in GitHub Desktop.
Save jhonnatas/46461dcdad3ef87477362f7351bbc5ad to your computer and use it in GitHub Desktop.
Ruby on Rails - Generating Scaffold with relationship
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.
I's not necessary run the generate command after put the has_many :comments.
reference: https://stackoverflow.com/questions/13445367/create-relationships-when-scaffolding
Thanks to JamieD.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment