Rails 迁移:t.references 具有替代名称?
所以我有一个像这样的学校课程的create_table:
create_table :courses do |t|
t.string :name
t.references :course
t.timestamps
end
但我希望它引用两个其他课程,例如:
has_many :transferrable_as # A Course
has_many :same_as # Another Course
我可以说以下吗?
t.references :transferrable_as, :as=> :course
So I have a create_table like this for Courses at a School:
create_table :courses do |t|
t.string :name
t.references :course
t.timestamps
end
but I want it to reference two other courses like:
has_many :transferrable_as # A Course
has_many :same_as # Another Course
Can I say the following?
t.references :transferrable_as, :as=> :course
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以在初始迁移/列定义中完成这一切(至少目前在 Rails 5 中):
You can do this all in the initial migration/column definition (at least currently in Rails 5):
您可以这样做:
或使用
t.belongs_to
作为t.references
的别名您不能将
foreign_key: true
添加到这些两条参考线。如果您想在数据库级别将它们标记为外键,您需要进行以下迁移:在 Rails 5.1 及更高版本中更新
,您可以在
create_table
块中的迁移中添加外键,如下所示:You can do it this way:
or using
t.belongs_to
as an alias fort.references
You can't add
foreign_key: true
to those two references lines. If you want to mark them as foreign keys at the database level you need to have a migration with this:Update
In Rails 5.1 and above you can add the foreign key in the migration in the
create_table
block like this:作为这个问题的补充答案——模型应该具有以下行来完成关联:
As an added answer to this question -- the Model should have the following line to complete the association:
我认为这个线程有一个不同的更 Rails 风格的方式:
脚手架 ActiveRecord:相同数据类型的两列
在迁移中:
I think this thread has a different more Rails-ish way:
Scaffolding ActiveRecord: two columns of the same data type
In the migration:
我认为
references
不接受:as
选项,但您可以手动创建列...I don't think
references
accepts the:as
option, but you can create your columns manually...