Skip to content

Instantly share code, notes, and snippets.

@leviwilson
Created July 1, 2011 02:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leviwilson/1057757 to your computer and use it in GitHub Desktop.
Save leviwilson/1057757 to your computer and use it in GitHub Desktop.
RoR Associations
#rails gen model Player name:string
class Player < ActiveRecord:Base
has_many :wins, :class_name => "Game", :foreign_key => "winner"
has_many :losses, :class_name => "Game", :foreign_key => "loser"
end
#rails gen model Game winner:integer loser:integer
class Game < ActiveRecord:Base
belongs_to :winner, :class_name => "Player", :foreign_key => "player_id"
belongs_to :loser, :class_name => "Player", :foreign_key => "player_id"
end
@leviwilson
Copy link
Author

Is this a completely wrong approach? It seems like I should be able to do this.

@leviwilson
Copy link
Author

Nevermind, looks like I had the Game record setup horribly :-) Here is what worked (I haven't tested "wins" and "losses" on the Player model yet)

class Game < ActiveRecord:Base
    belongs_to :player, :foreign_key => "winner"
    belongs_to :player, :foreign_key => "loser"
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment