Rails中的多级关联 [英] Multi level associations in rails

查看:95
本文介绍了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.

推荐答案

简单的答案是:

class Fixture < ActiveRecord::Base
  belongs_to :home_team, :class_name => "Team", :foreign_key => :home_team
  belongs_to :away_team, :class_name => "Team", :foreign_key => :away_team
end

class Team < ActiveRecord::Base
  has_many :fixtures
end

但是如果您这样做,那是不好的,因为Team.fixtures无法正常工作.

But this is no good if you because Team.fixtures will not work.

class Team < ActiveRecord::Base
  has_many :home_fixtures, :class_name => "Fixtures", :foreign_key => :home_team
  has_many :away_fixtures, :class_name => "Fixtures", :foreign_key => :away_team
end

将为您提供两个收藏夹...但是将它们汇总起来必须在红宝石中进行,这会很棘手.

will give you two collections… but aggregating them will have to happen in ruby, which will be icky.

class Team < ActiveRecord::Base
  def fixtures(*args)
    home_fixtures.all(*args) + away_fixtures.all(*args)
  end
end

这也有问题,排序和限制都将增加(嘿,双关语,谁知道?).

This has it's problems too, sort and limit will be all ballsed up (heh, a pun, who knew?).

class Team < ActiveRecord::Base
  has_many :fixtures, :finder_sql => 'SELECT * FROM fixtures where (home_team = #{id} or away_team = #{id})'
  has_many :home_fixtures, :class_name => "Fixtures", :foreign_key => :home_team
  has_many :away_fixtures, :class_name => "Fixtures", :foreign_key => :away_team
end

这很丑陋,但可能会起作用. finder_sql似乎可以完成所需的工作.

This is ugly, but may just work. The finder_sql seems to do what's needed.

另一种选择是使用named_scope:

The other option is to use a named_scope:

class Fixture < ActiveRecord::Base
  named_scope :for_team_id, lambda{|team_id| {:conditions => ['(home_team = ? or away_team = ?)', team_id, team_id]} }
  belongs_to :home_team, :class_name => "Team", :foreign_key => :home_team
  belongs_to :away_team, :class_name => "Team", :foreign_key => :away_team
end

class Team < ActiveRecord::Base
  def fixtures
    Fixtures.for_team_id(id)
  end
end

最后一个解决方案是我坚持使用的解决方案,因为它是一个作用域,它的行为很像只读关联,并且可以防止在以后发生的:finder_sql古怪现象(我的意思是真的吗?它知道如何合并更多条件?有时它需要一个子查询,一个子查询?在这里不需要吗?).

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? ).

希望这会有所帮助.

这篇关于Rails中的多级关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆