首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ruby on Rails -有一个或多个关联

Ruby on Rails -有一个或多个关联
EN

Stack Overflow用户
提问于 2014-02-14 06:55:41
回答 2查看 629关注 0票数 0

因此,我一直在思考如何为我的应用程序建立关联,但每次我从一个角度看一个模型时,我都会发现它没有意义或效率低下。

我有三个模型:锦标赛,RoundRobin和淘汰赛。锦标赛可以是round_robin或淘汰赛,也可以是两者兼而有之!因此,round_robin或/和淘汰赛属于锦标赛。

我的情况是,我建立的联想是有趣的,对我来说没有任何意义。

代码语言:javascript
复制
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和淘汰赛?

提前感谢

EN

回答 2

Stack Overflow用户

发布于 2014-02-14 07:22:31

也许你应该只有一个'kind‘列的桌上锦标赛。例如,如果该锦标赛是RoundRobin,如果该锦标赛是淘汰赛,如果kind=1 kind=2该锦标赛是淘汰赛,那么该锦标赛既是淘汰赛又是RoundRobin。

票数 0
EN

Stack Overflow用户

发布于 2014-02-14 07:26:05

编辑:由于你不是在挖掘STI,另一种选择是有两种类型的锦标赛(循环赛和淘汰赛),这两种belongs_to锦标赛。

因此,在这种情况下:

代码语言:javascript
复制
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锦标赛,它可以从锦标赛中获得所有基本的东西:

代码语言:javascript
复制
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。

代码语言:javascript
复制
#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...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21767352

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档