47

Is there a way to generate has_many association for a column using Rails generate scaffold command in the console?

I know belongs_to is available and there are use cases of references but not sure of has_many

Passionate Engineer
  • 10,034
  • 26
  • 96
  • 168

1 Answers1

91

There is no column for a has_many relationship. A belongs_to is backed by a column which holds a foreign key.

So if you generate a scaffold: rails g scaffold Post

And then you generate another scaffold: rails g scaffold Comment post:references

Then rails will create a migration that adds a column named post_id to the Comment table and creates an index on it. For both tables, it creates foreign key constraints between comments(post_id) and posts(id). Rails will also add belongs_to :post in the Comment model.

At anytime you can add a has_many to a model as long as another model belongs_to the first model and has a migration with the foreign key column.

Chris Kerlin
  • 130
  • 1
  • 4
Alex Peachey
  • 4,606
  • 22
  • 18
  • 1
    I wonder, can a model that is the "one-side" in a one-many relation not be defined in a single "rails generate model" command (?) – Valter Ekholm Nov 30 '20 at 12:32