Complexe关系(has_many / belongs_to)Ruby On Rails

时间:2018-06-12 13:33:45

标签: ruby-on-rails ruby-on-rails-5 rails-migrations

我对复杂的关系有疑问。我有3个桌子" SPORTS"," AREAS"," TOURNAMENTS"。 一项运动可能有多个区域,一个区域可能与多项运动相关联。比赛与一个区域和一项运动相关联。

示例:

Sport 1: Baseball
Sport 2: Football
Sport etc...
Sport 5: Handball

Area 1: Germany
Area 2: Italy
Area etc...

Tournament 1: World Cup
Tournament etc...

说明:

Sport 1 linked to Area 1 & 2
Sport 5 linked to Area 1 & 2 

So Area 1 linked to Sport 1 & 5

Tournament linked to Sport 1 and Area 1

如何做所有这些关系?如何从运动(例如1)中找到附加的锦标赛数量? (通过?)

我对此进行了测试,但我不确定:

模特体育:

class Sport < ApplicationRecord
    has_and_belongs_to_many :area
    has_many :tournaments,
       through: :areas,
       source: :tournaments,
       class_name: 'Tournament'
end

型号区域:

class Area < ApplicationRecord
    has_and_belongs_to_many :sports
    has_many :tournaments
end

模特锦标赛:

class Tournament < ApplicationRecord
    belongs_to :sport
    belongs_to :area
end

0 个答案:

没有答案