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