0

I'm pretty new to rails and trying to figure out relationships.

The data I'm trying to model is as follows: An Event is a gathering where people play games. An Event is recorded in multiple Videos. A Video contains multiple GameSets. A GameSet has two Players, player_one and player_two.

Because an Event has many Videos, and a Video has many GameSets, I feel like I should be able to declare a has_many :through relationship to get straight from an Event to GameSets. Also, I should be able to go straight from a player to all of the GameSets that he has participated in.

Here's what I have:

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

But when I try to execute code like:

GameSet.find_by_id(1).player_one 

I get the following exception.

?[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

I can't for the life of me figure out what it is I'm doing wrong. Any help is appreciated.

4

1 回答 1

0

Your relationships between GameSet and its players are wrong. Assuming you have two integer columns with the ids for player_one and player_two, the relationship should be belongs_to instead of has_one. Otherwise, it would mean that it's Player that has a game_set_id to link back to GameSet.

于 2013-02-03T22:21:21.207 回答