Rails 中的多级关联
我正在创建一个应用程序来跟踪足球队整个赛季的情况。但我坚持数据库的设计。一场比赛有主队和客队。我创建了一个固定模型,它有两个外键 - home_team 和away_team,但我无法让关联正常工作。有什么想法吗?每场比赛都属于一个联赛。
I am creating an application to track football teams through out the season. but i am stuck on the design of the database. One fixture has a home team and an away team. I have created a fixture model which has two foreign keys- home_team and away_team but I cant get the association to work right. any ideas? Each fixture belongs to a league.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简单的答案是:
但这并不好,因为 Team.fixtures 不起作用。
会给你两个集合……但是聚合它们必须在 ruby 中进行,这会很麻烦。
这也有它的问题,排序和限制将全部搞砸(呵呵,双关语,谁知道呢?)。
这很丑陋,但可能可行。 finder_sql 似乎可以满足需要。
另一种选择是使用named_scope:
最后一个解决方案是我坚持使用的解决方案,因为它是一个作用域,它的行为非常类似于只读关联,并防止可能出现的
:finder_sql
怪异行为。发生在更远的地方(我的意思是真的吗?它怎么知道如何合并更多条件?它有时会执行子查询,子查询?这只是这里不需要的?)。希望这有帮助。
The simple answer is:
But this is no good if you because Team.fixtures will not work.
will give you two collections… but aggregating them will have to happen in ruby, which will be icky.
This has it's problems too, sort and limit will be all ballsed up (heh, a pun, who knew?).
This is ugly, but may just work. The finder_sql seems to do what's needed.
The other option is to use a named_scope:
This last solution is the one I'd stick with, because it's a scope it will behave much like a read only association, and prevents the
:finder_sql
wackiness that may happen further down the line (I mean really? How does it know how to merge more conditions? It sometimes does a subquery, a subquery? Thats just not needed here? ).Hope this helps.
假设您有一个
Team
模型和一个Something
模型,后者将具有home_team_id
和away_team_id
。您将把它们称为
something.away_team
和something.home_team
。Say that you have a
Team
model and aSomething
Model, the latter will havehome_team_id
andaway_team_id
.You will refer to them as
something.away_team
andsomething.home_team
.