Forum: Ruby on Rails figuring out ActiveRecord associations

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Dondi S. (Guest)
on 2007-07-30 06:57
Hi folks,

This is my first post to the list. I was hoping someone could help me
with setting up ActiveRecord associations on a project I recently
started.

The project is a web-based game.  Actually, the application will have
multiple "game" instances, and "users" may play as a "player" in more
than one game instance at a time. The part I'm having trouble with is
how to express with ActiveRecord that a "user" can only be one "player"
in each "game." I have so far:
  user has_many players
  game has_many players
  player belongs_to game
  player belongs_to user

What I want is "user has_one :player, :per => :game". I tried to use
"through," but that is not an option for "has_one."

If I was doing this without an ORM, I would set up my database schema
like this

create table games (
id not null primary key
other_columns...
);

create table users (
id not null primary key
username not null
password not null
other_columns...
);

create table players (
id not null primary key
game_id not null
user_id not null
UNIQUE (game_id, user_id)
);

Thanks for any insight. After several years of web development using
only raw SQL for the database part, I've learned to think in SQL, and
I'm having a hard time figuring out what to do once it's abstracted
away.
Dondi S. (Guest)
on 2007-08-01 02:02
I think I figured it out. I guess what I wanted was this:

class Player
  validates_uniqueness_of :user_id, :scope => :game_id, :message => "may
be one player in each game"
  ...
end
This topic is locked and can not be replied to.