Rails: How to migrate a database where I added a :belongs_to relationship?

北城以北 提交于 2019-12-25 03:56:12

问题


This is my first rails app, one I'm creating for the sole purpose of learning rails.

I created an app where I have Users and Products (and sessions, but this is not relevant here). After doing a rake db:mograte creating a few items and testing, I then wanted to add a relationship, where products belongs_to :users and a users has_many :products.

But of course, since I have already created the tables, there isn't any column there to save this information.

How do I make a migration on the database so it will reflect this model? Is there a console tool for it? Do I have to install a third party gem?


回答1:


You can generally add columns right from the command line. Here is an example that might be relevant to your situation:

In the terminal, navigate to your Rails app and type:

rails generate migration add_user_id_to_products user_id:integer

This will create a migration automatically that has the user_id column in the products table. You can then migrate the database again to add the latest changes:

rake db:migrate

You should then have the minimum required for your has_many/belongs_to relationship.



来源:https://stackoverflow.com/questions/8420769/rails-how-to-migrate-a-database-where-i-added-a-belongs-to-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!