通过迁移设置外键关联

时间:2016-03-06 17:18:48

标签: ruby-on-rails ruby associations referential-integrity

我的项目有以下表格图表:

  • Campeonato =冠军赛(这是一项赛事)
  • Especial = Special(也是一个事件)

[diagram]

我想制作属于锦标赛的大奖赛。这种关系是1:n协会。一场大奖赛总是属于一个冠军赛或一场特殊赛事#34;。

我正在制作模型并使用其列编写迁移,但我不知道如何在迁移中表达关联。

我有以下迁移的代码:

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

我不知道这是否是引用外键的正确方法。

总而言之,我有三个实体:

  • 冠军
  • 特殊
  • GPS

GPS属于至少一个锦标赛或一个特殊锦标赛。我想知道在我的迁移中显示正确的方法。

3 个答案:

答案 0 :(得分:0)

您可以使用t.references :champtionship

通过选项根据您的需求定制:

  • foreign_key

但您也可以添加一个名为champtionship_id的整数列,并使用add_foreign_key手动添加外键

答案 1 :(得分:0)

您对此解决方案有何看法?

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

并重复此过程为Special&amp;全球定位系统?

答案 2 :(得分:0)

如果您的GPS属于至少一个冠军或一个特殊但不是两个。您可以使用polymorphic关联。

以下是你的模特:

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 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

有关详细信息,请参阅polymorphic associations