0

我在试图找出关联/加入我的表“团队”和“时间表”的最佳方式时遇到了麻烦。我的模型是:

class Team < ActiveRecord::Base
  attr_accessible :city, :conf, :div, :key, :name
  self.primary_key = "key" #Abbreviations for strings 'CHI', 'TB', 'SEA' etc.

  has_many :schedules, foreign_key: [:away_team, :home_team]
end

class Schedule < ActiveRecord::Base
  attr_accessible :away_team, :date, :home_team, :season, :week, :team_key
  self.primary_keys = :away_team, :home_team #Abbreviations for strings 'CHI', 'TB', 'SEA' etc.

  belongs_to :team, primary_key: "key"
end

我安装了 gem “composite_primary_keys”,“~> 5.0.13”。

在我分配变量时在rails控制台中

>> team = Team.find("SEA")

SELECT "teams".* FROM "teams" WHERE "teams"."key" = ? LIMIT 1  [["key", "SEA"]]
=> #<Team key: "SEA", city: "Seattle", name: "Seahawks", conf: "NFC", div: "West">

它完美地显示了西雅图,但是当我运行时:

>> team.schedules

SELECT "schedules".* FROM "schedules" WHERE ("schedules"."away_team" = 'SEA' AND "schedules"."home_team" IS NULL) 
=> []

'schedule' 表的 home_team 列中有 'SEA' 的数据。

连接表会是更好的解决方案吗?如果是这样,你会怎么做?任何帮助将不胜感激!

4

1 回答 1

1

第一:不要使用复合键,如果你不需要(在这种情况下你不需要)。
主键用于访问单个项目,而不是用于约束或业务逻辑。
在您的情况下,主索引不能用于 home_team 选择时间表。

尽可能多地使用 Rails 约定也是一个好主意。它使生活更轻松。用id作主键和连接表。

我看到你的日程分属于两个球队,球队有两种日程(主场和客场)。所以你的模型可能看起来像:

class Team < ActiveRecord::Base
  attr_accessible :city, :conf, :div, :key, :name

  has_many :home_schedules, class_name: 'Schedule', foreign_key: :home_team_id
  has_many :away_schedules, class_name: 'Schedule', foreign_key: :away_team_id

  def schedules
    home_schedules + away_schedules
  end
end

class Schedule < ActiveRecord::Base
  attr_accessible :away_team, :date, :home_team, :season, :week, :team_key

  belongs_to :home_team, class_name: 'Team'
  belongs_to :away_team, class_name: 'Team'
end

然后

team = Team.find_by_key('SEA')
team.schedules

添加

我会生成模型

rails g model Team city conf div short_cut name
rails g model Schedule day:date season week:integer home_team_id:integer away_team_id:integer

您可以通过添加 将球队与球迷联系team_id起来Fan。您始终可以使用团队的快捷方式(我将您以前的关键属性命名为)来显示或选择团队,但让 Railsid用于所有内部内容。

于 2013-05-30T09:21:30.200 回答