Rails generate has_many association

后端 未结 1 1227
一整个雨季
一整个雨季 2021-01-30 13:12

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 availab

相关标签:
1条回答
  • 2021-01-30 14:07

    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.

    0 讨论(0)
提交回复
热议问题