Rails关系:在多对多关系中引用同一个表两次

时间:2013-02-03 22:16:25

标签: ruby-on-rails has-many-through rails-activerecord has-and-belongs-to-many

我对rails非常陌生,并试图找出关系。

我正在尝试建模的数据如下: 活动是人们玩游戏的聚会。 一个事件记录在多个视频中。 视频包含多个GameSet。 GameSet有两个玩家,player_one和player_two。

因为一个事件有很多视频,而一个视频有很多GameSet,我觉得我应该能够声明一个has_many:through关系来直接从一个事件到GameSet。此外,我应该可以直接从玩家到他参与的所有GameSet。

这就是我所拥有的:

class Event < ActiveRecord::Base
  attr_accessible :event_date, :event_name, :event_number, :city, :state, :game_sets, :videos
  has_many :videos
  has_many :game_sets, :through => :videos
end

class Video < ActiveRecord::Base
  attr_accessible :name, :url, :event, :game_sets
  belongs_to :event
  has_many :game_sets
end

class GameSet < ActiveRecord::Base
  attr_accessible :player_one, :player_two, :video
  belongs_to :video
  has_one :player_one, :class_name => "Player"
  has_one :player_two, :class_name => "Player"
end

class Player < ActiveRecord::Base
  attr_accessible :first_name, :handle, :home_city, :home_state, :last_name, :tag
  has_and_belongs_to_many :game_sets
end

但是当我尝试执行以下代码时:

GameSet.find_by_id(1).player_one 

我收到以下异常。

?[1m?[36mGameSet Load (0.0ms)?[0m  ?[1mSELECT "game_sets".* FROM "game_sets" WHERE "game_sets"."id" = 1 LIMIT 1?[0m  ?[1m?[35mPlayer Load (1.0ms)
?[0m  SELECT "players".* FROM "players" WHERE "players"."game_set_id" = 1 LIMIT 1SQLite3::SQLException: no such column: players.game_set_id: SELECT  "players".* FROM "players"  WHERE "players"."game_set_id" = 1 LIMIT 1ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: players.game_set_id: SELECT  "players".* FROM "players"  WHERE "players"."game_set_id"= 1 LIMIT 1

我不能为我的生活弄清楚我做错了什么。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

GameSet与其玩家之间的关系是错误的。假设你有两个带有player_one和player_two的id的整数列,那么关系应该是belongs_to而不是has_one。否则,这意味着它的Player有一个game_set_id链接回GameSet。