Skip to content

Instantly share code, notes, and snippets.

@verygreenboi
Created January 14, 2014 12:38
Show Gist options
  • Save verygreenboi/8417661 to your computer and use it in GitHub Desktop.
Save verygreenboi/8417661 to your computer and use it in GitHub Desktop.
class CreateBase < ActiveRecord::Migration
def up
create_table :games do |t|
t.integer :home_team_id, :null => false
t.integer :away_team_id, :null => false
t.integer :score, :null => false
end
create_table :teams do |t|
t.string :team_name, :null => false
end
end
end
# ---------------------------------------------------------------------
class Teams < ActiveRecord::Base
has_many :away_games, :foreign_key => :away_team_id, :class_name => Games
has_many :home_games, :foreign_key => :home_team_id, :class_name => Games
end
class Games < ActiveRecord::Base
belongs_to :home_team, :foreign_key => :home_team_id, :class_name => Teams
belongs_to :away_team, :foreign_key => :away_team_id, :class_name => Teams
end
# ---------------------------------------------------------------------
Teams.new(:team_name => :foo)
Teams.new(:team_name => :bar)
Games.new(:home_team_id => 1, :away_team_id => 2, :score => 10)
# ---------------------------------------------------------------------
Games.first.away_team # => #<Teams id: 2, team_name: "bar">
Games.first.home_team # => #<Teams id: 1, team_name: "foo">
# ---------------------------------------------------------------------
Teams.first.home_games # => [#<Games id: 1, home_team_id: 1, away_team_id: 2, score: 10>]
Teams.first.away_games # => []
# ---------------------------------------------------------------------
Teams.last.home_games # => []
Teams.last.away_games # => [#<Games id: 1, home_team_id: 1, away_team_id: 2, score: 10>]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment