Easy Rails 问题:模型和迁移

发布于 2024-09-11 07:54:57 字数 150 浏览 1 评论 0原文

每当我更改 Rails 中的模型时,是否需要重新迁移?有人能告诉我迁移到底有什么作用吗?我正在阅读它,我对 db/migrate 内的内容和 app/models 内的内容之间的区别有些困惑。

例如,如果我在模型中添加 has_one 关系,是否需要重新迁移它?为什么?

Do I need to re-migrate whenever I change the models in Rails? Can someone tell me what migration really does? I am reading it and I am somewhat confused with the difference between the stuff inside db/migrate and the stuff inside app/models.

For example, if I add a has_one realtionship inside my model, do I need to re-migrate this? Why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

給妳壹絲溫柔 2024-09-18 07:54:57

如果您的数据库发生更改,请使用迁移。如果您只是向模型添加方法,则无需进行迁移。

示例:

我们一开始只有名字和姓氏。我们想要将它们存储在数据库中,所以我们有一个迁移:

/app/models

# empty

/ human.rb /db/migrate/xxxxx.rb

add_column :humans, :first_name, :string
add_column :humans, :last_name, :string

然后我们结婚了,所以我们想要跟踪

/app/models/ human .rb

belongs_to :spouse
  • 我们需要在数据库中有一个配偶_id 字段,所以我们需要一个迁移

/db/migrate/xxxxx.rb

add_column :humans, :spouse_id, :integer
  • 然后我们就有一个孩子......事实上,我们都曾经是孩子,但要保留它简单,我们将拥有人类和后代

/app/models/offspring.rb

belongs_to :human

/db/migrate/xxxxx.rb

create_table ... 
  • 但是,无需向人类迁移添加任何内容,因为此处没有表更改。我们确实需要添加:

/app/models

has_many :offspring
  • / human.rb 如果您希望能够轻松地获得您的长子,您只需向模型添加一个方法即可。这里不需要迁移:

/app/models/ human.rb

def first_born
  offspring.first
end

If your database changes, use a migration. If you're just adding methods to your model, no need to have a migration.

Example:

We start out and we just have first_name, last_name. We want to store those in the database, so we have a migration that does:

/app/models/human.rb

# empty

/db/migrate/xxxxx.rb

add_column :humans, :first_name, :string
add_column :humans, :last_name, :string

Then we get married, so we want to track that

/app/models/human.rb

belongs_to :spouse
  • We need to have a spouse_id field in the database, so we need a migration

/db/migrate/xxxxx.rb

add_column :humans, :spouse_id, :integer
  • We then have a kid.... In fact, we were all kids at one point, but to keep it simple, we'll have Humans and Offspring

/app/models/offspring.rb

belongs_to :human

/db/migrate/xxxxx.rb

create_table ... 
  • However, no need to add anything to the Human migration, since no tables change here. We do need to add:

/app/models/human.rb

has_many :offspring
  • If you want to be able to get at, easily, your first born, you'd just add a method to your model. No need for a migration here:

/app/models/human.rb

def first_born
  offspring.first
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文