Forum: Ruby on Rails Is there AR magic for this?

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.
Gregory S. (Guest)
on 2006-04-05 15:35
(Received via mailing list)
I am working on a game system. My models include User, Game, and Player:

User has_many Players
Game has_many Players
Player belongs_to User, Game

Basically, Player is a join table between User and Game, but since there
is
information that is specific to the relationship I want it to be a model
in
its own right. The part where I'd like some AR magic is that given a
User
(the id is in the session) and a Game (the id is part of the URL), I
want
to find the Player (assuming there is one) relating them. My current
implementation looks something like this (pseudocode):

@user = User.find(session[:user_id])
@game = Game.find(params[:id])
@player = @game.players.detect { |p| p.user_id = @user.id }

It works, and I'm likely to use the players list later anyway, but I
feel
like there should be a simple way to get the Player without loading all
the
players. I suppose Player.find_by_game_id_and_user_id(@game.id,
@user.id)
would work, but it isn't a whole lot nicer. I'm hoping for something
like
Player.find_by_owners(:user => @user, :game => @game).

--Greg
This topic is locked and can not be replied to.