Ruby on rails 通过迁移设置外键关联
我的项目有以下表格图表:Ruby on rails 通过迁移设置外键关联,ruby-on-rails,ruby,associations,referential-integrity,Ruby On Rails,Ruby,Associations,Referential Integrity,我的项目有以下表格图表: Campeonato=锦标赛(这是一项赛事) 特别的(这也是一个事件) [] 我想创造属于锦标赛的大奖赛。这种关系是1:n的关联。一场大奖赛总是属于一个冠军或一个“特殊事件” 我正在制作模型并编写迁移及其列,但我不知道如何表达迁移中的关联 我有以下迁移代码: class CreateGrandPrixes < ActiveRecord::Migration def change create_table :grand_prixes do |t|
- Campeonato=锦标赛(这是一项赛事)
- 特别的(这也是一个事件)
class CreateGrandPrixes < ActiveRecord::Migration
def change
create_table :grand_prixes do |t|
t.datetime :gp_date
t.integer :max_slots
## Relationship
t.belongs_to :championship, index: true
t.belongs_to :special, index: true
t.timestamps null: false
end
end
end
class CreateGrandPrixes
我不知道这是否是引用外键的正确方法
总而言之,我有三个实体:
- 冠军赛
- 特别的
- 全球定位系统
全球定位系统至少属于一项锦标赛或一项特殊赛事。我想知道如何在我的迁移过程中展示这一点 您可以使用
t.references:championship
并通过以下选项根据您的需要定制:
- 外键
- 空的
但是您也可以只添加一个名为
championship\u id
的整数列,然后使用add\u foreign\u key
手动添加外键,您认为这个解决方案怎么样
class CreateJoinTableChampionshipGrandPrix < ActiveRecord::Migration
def change
create_join_table :championships, :grand_prixes do |t|
# t.index [:championship_id, :grand_prix_id]
# t.index [:grand_prix_id, :championship_id]
end
end
end
class CreateJoinTableChampionshipGrandPrix
对特殊和GPs重复此过程 如果您的GPS至少属于一项锦标赛或一项特别赛事,但不是同时属于两项赛事。您可以使用多态关联 以下是您的模型:
class Campeonato < ActiveRecord::Base
self.table_name = 'Campeonato'
self.primary_key = 'id_evento'
has_one :gp, as: :eventable
end
class Especial < ActiveRecord::Base
self.table_name = 'Especial'
self.primary_key = 'id_evento'
has_one :gp, as: :eventable
end
class Gp < ActiveRecord::Base
self.table_name = 'Gps'
self.primary_key = 'id_gp'
belongs_to :eventable, polymorphic: true
end
class Campeonato
以下是相应的迁移:
class CreateCampeonato < ActiveRecord::Migration
def change
create_table 'Campeonato', id: true, primary_key: 'id_evento' do |t|
#add other fields
end
end
end
class CreateEspecial < ActiveRecord::Migration
def change
create_table 'Especial', id: true, primary_key: 'id_evento' do |t|
#add other fields
end
end
end
class CreateGps < ActiveRecord::Migration
def change
create_table 'Gps', id: true, primary_key: 'id_gp' do |t|
t.string :event_type # to store the class name (ex: Campeonato or Especial)
t.integer :event_id # to store the primary_key of Campeonato or Especial
#add other fields
end
end
end
class CreateCampeonato
有关更多信息,请参阅。谢谢您的回复。我确实有更多的“问题”。我的GP可能属于锦标赛或特殊实体。我如何设置大奖赛是冠军赛还是特别赛?我的意思是你说我可以做以下事情:GP|U表| id| gps | id|冠军| id|轨道| GP|U日期| max|槽,但它也可以是一个特殊的,所以我可以介绍另一个立柱作为参考:| id|U gps | id|冠军| id|特殊| id|轨道| GP|日期| max|槽对不起,我在这里有点迷路了:SPerhaps你想看看吗多态关联。