因此,我一直在思考如何为我的应用程序建立关联,但每次我从一个角度看一个模型时,我都会发现它没有意义或效率低下。
我有三个模型:锦标赛,RoundRobin和淘汰赛。锦标赛可以是round_robin或淘汰赛,也可以是两者兼而有之!因此,round_robin或/和淘汰赛属于锦标赛。
我的情况是,我建立的联想是有趣的,对我来说没有任何意义。
class Tournament < ActiveRecord::Base
has_many :round_robins
has_many :eliminations
end
class Elimination < ActiveRecord::Base
belongs_to :tournament
end
class RoundRobin < ActiveRecord::Base
belongs_to :tournament
end我还有另一个模型叫Match。我不知道该怎么摆放。它应该归入锦标赛还是RoundRobin和淘汰赛?
提前感谢
发布于 2014-02-14 07:22:31
也许你应该只有一个'kind‘列的桌上锦标赛。例如,如果该锦标赛是RoundRobin,如果该锦标赛是淘汰赛,如果kind=1 kind=2该锦标赛是淘汰赛,那么该锦标赛既是淘汰赛又是RoundRobin。
发布于 2014-02-14 07:26:05
编辑:由于你不是在挖掘STI,另一种选择是有两种类型的锦标赛(循环赛和淘汰赛),这两种belongs_to锦标赛。
因此,在这种情况下:
class Tournament < ActiveRecord:Base
has_many :matches
#attributes specific to any type of tournament: name, date, etc.
end
class RoundRobin < ActiveRecord:Base
belongs_to :tournament
#adds attributes specific to round robin tournaments
end
#etc
class Elimination < ActiveRecord:Base
belongs_to :tournament
#has attributes specific to elimination tournaments
end
class Match
belongs_to :tournament
end因此,如果你有一个round_robin锦标赛,它可以从锦标赛中获得所有基本的东西:
round_robin = RoundRobin.find(1)
#get tourney name
puts round_robin.tournament.name
puts round_robin.tournament.match.team_one_name #allowing you to access the match as well...如果你想,你可以在锦标赛上有一个名为type的属性(让你知道它是哪一个)。在rails中,这些都是传统的字符串。但在其他语言中,我们通常使用带有外键的lookup_tables。
#to find all round_robins
tournaments = Tournament.find_by_type("round_robin")
tournmaments.each do |tourney|
round_robin = RoundRobin.find_by_tournament_id(tourney.id)
end
#there are actually a bunch of different ways to query these:
round_robins = RoundRobin.all
tournaments = Tournament.joins(:round_robin).where("tournament_date > ?", date_lookup)
etc...https://stackoverflow.com/questions/21767352
复制相似问题