Rails:如何迁移添加了 :belongs_to 关系的数据库? [英] Rails: How to migrate a database where I added a :belongs_to relationship?

查看:42
本文介绍了Rails:如何迁移添加了 :belongs_to 关系的数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一个 rails 应用程序,我创建的唯一目的是学习 rails.

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

我创建了一个应用程序,其中包含用户和产品(以及会话,但这与此处无关).在执行 rake db:mograte 创建一些项目并进行测试之后,我想添加一个关系,其中产品属于 :users 和用户 has_many :products.

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.

如何在数据库上进行迁移以反映此模型?是否有控制台工具?我是否必须安装第三方 gem?

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?

推荐答案

您通常可以直接从命令行添加列.下面是一个可能与您的情况相关的示例:

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

在终端中,导航到您的 Rails 应用并输入:

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

rails generate migration add_user_id_to_products user_id:integer

这将自动创建一个在产品表中具有 user_id 列的迁移.然后您可以再次迁移数据库以添加最新更改:

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

然后,您的 has_many/belongs_to 关系应该达到最低要求.

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

这篇关于Rails:如何迁移添加了 :belongs_to 关系的数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆