On Apr 7, 2006, at 9:07 AM, Andrew C. wrote:
That is, does rails know that because games has player1_id and
player2_id that games.player1 and games.player2 are objects from the
You can see I am confused!
I believe what you actually need is a has_one relationship. Although
the game does have many players, the way the table is set up, it only
has one player1 and one player2. Try this:
class Game < ActiveRecord::Base
has_one :player1, :class_name => ‘Player’
has_one :player2, :class_name => ‘Player’
You need to specify the class name because otherwise it will look for
a class called Player1 which of course doesn’t exist. You should then
be able to use game.player1 or game.player2 to access the players.
However, you may find this database design will cause problems later.
If, for example, you want to support more than two players, you will
need to add more columns for player3, player4, etc. Then what if you
want to support, say 16 players. That is a lot of columns and could
get messy! If this is at all a possibility, you should go with a true
You would do this by putting a game_id column in the players table
and removing the player1 and player2 columns from the games table.
You could then use the “has_many :players” relationship method in
your Game model. You can then grab the players with game.players
or game.players, etc. This also allows you to iterate through all
players instead of having to refer to each one individually.