Rails: How to migrate a database where I added a :

2019-08-19 05:36发布

问题:

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.