ROR 3 model associations

Hi all,

I am new to ROR3 and would really appreciate some advice on how to
define the following model association:

Game model - has host_userid and visitor_userid as fields to define
the two players engaged in the game. this two
                      fields are of type User and need to be mapped
via foreign key relationship.

User model - a user object can belong to one or more games (as I
imagine .. I would fetch that by querying the
                     Games table where the host_userid or
visitor_userid equal to the userid in question)

if anyone could post a code snippet to define such associations Id be
really grateful :slight_smile:

If you phrase it slightly differently, the code for associations almost writes itself:

Game has one host to class User
Game has one visitor to class User

User has many hosting games to class Game
User has many visiting games to class Game

By default when you create an association, rails will use the model name plus “_id” to determine the foreign key. This isn’t what you want, since game has 2 foreign keys to user. Adding the class_name option makes it use the name of the association and the class name plus “_id”. In this case, host_user_id and visitor_user_id.

So you can define it like this:

class Game
has_one :host, :class_name => User, :inverse_of => :hosting_games
has_one :visitor, :class_name => User, :inverse_of => :visiting_games

class User

has_many :hosting_games, :class_name => Game, :inverse_of => :host
has_many :visiting_games, :class_name => Game, :inverse_of => :visitor