# Figuring out ActiveRecord associations

**URL:** <https://www.ruby-forum.com/t/figuring-out-activerecord-associations/110717>\
**Category:** Rails\
**Created:** [July 30, 2007, 4:57am UTC](https://www.ruby-forum.com/t/figuring-out-activerecord-associations/110717 "2007-07-30T04:57:59Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dmspilot00](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/779978/32.png) [@dmspilot00](https://www.ruby-forum.com/u/dmspilot00)\
**Post date:** [July 30, 2007, 4:57am UTC](https://www.ruby-forum.com/t/figuring-out-activerecord-associations/110717/1 "2007-07-30T04:57:59Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![dmspilot00](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/779978/32.png) [@dmspilot00](https://www.ruby-forum.com/u/dmspilot00)\
**Post date:** [August 1, 2007, 12:02am UTC](https://www.ruby-forum.com/t/figuring-out-activerecord-associations/110717/2 "2007-08-01T00:02:35Z")

</div>

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
