Rails 3:belongs_to、has_one 和 Migrations [英] Rails 3: belongs_to, has_one and Migrations
问题描述
我是 Rails 的新手,我是从 Django 背景开始学习的.我已经接受了这样一个事实,即模型和数据库模式在 Rails 在线 Django 中是分开的.但是,我仍在处理迁移问题.
I'm new to Rails, and I'm coming to it from a Django background. I've come to terms with the fact that models and the database schema are separate in Rails, online Django. However, I'm still getting to grips with migrations.
我的问题相当简单 - 如何使用迁移向模型添加关系?例如,我将 Artist
和 Song
作为空模型,它们现在是 ActiveRecord::Base
的子类,没有任何关系.
My question is fairly simple - how do I add a relationship to a model using a migration? For example, I have Artist
and Song
as empty models that subclass ActiveRecord::Base
at the moment, with no relationships whatsoever.
我需要开始这样做:
class Artist < ActiveRecord::Base
has_many :songs
end
class Song < ActiveRecord::Base
belongs_to :artist
end
但是如何使用 rails g migrate
更改架构以反映这一点?我使用的是 Rails 3.1.3.
But how do I change the schema to reflect this using rails g migrate
? I'm using Rails 3.1.3.
推荐答案
您必须在迁移文件中添加外键,如下所示:
You have to add the foreign key in your migration file, something like this:
def change
create_table :songs do |t|
t.references :artist
end
add_index :songs, :artist_id
end
这篇关于Rails 3:belongs_to、has_one 和 Migrations的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!