简体   繁体   中英

Rails Join table with two foreign keys from the same model

I'm trying to model contests, games, teams.

class Contest < ActiveRecord::Base
 has_many :games
end 

class Game < ActiveRecord::Base
 belongs_to :contest
 belongs_to :away_team, :class_name => "Team", :foreign_key => :away_team_id
 belongs_to :home_team, :class_name => "Team", :foreign_key => :home_team_id
end

class Team < ActiveRecord::Base
 belongs_to :sport
 has_many :away_teams, :class_name => "Game", :foreign_key => :away_team_id
 has_many :home_teams, :class_name => "Game", :foreign_key => :home_team_id
end

Migration for Game:

class CreateGames < ActiveRecord::Migration
 def change
  create_table :games do |t|
   t.references :contest, index: true, foreign_key: true
   t.integer :home_team_id, index: true, foreign_key: true
   t.integer :away_team_id, index: true, foreign_key: true

   t.timestamps null: false
   end
  end
 end

The game model will need to reference the team model twice to get away_team_id and home_team_id. I don't think this set-up is right because I can't access the away_team_id and home_team_id variables when messing around with a game object in console.

Any pointers?

I had to uncomment

permit_params :list, :of, :attributes, :on, :model, :contest_id, :away_team_id, :home_team_id

in app/admin/game.rb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM