Rails generate has_many association

2020-05-13 14:43发布

问题:

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

回答1:

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.