我在试图找出关联/加入我的表“团队”和“时间表”的最佳方式时遇到了麻烦。我的模型是:
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' 的数据。
连接表会是更好的解决方案吗?如果是这样,你会怎么做?任何帮助将不胜感激!