Rails使用同一模型中的两个外键连接表

时间:2015-10-05 01:19:14

标签: ruby-on-rails activerecord has-many belongs-to jointable

我正在尝试为比赛,比赛和球队建模。

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

游戏迁移:

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

游戏模型需要两次引用团队模型才能获得away_team_id和home_team_id。我不认为这个设置是正确的,因为当在控制台中弄乱游戏对象时,我无法访问away_team_id和home_team_id变量。

任何指针?

1 个答案:

答案 0 :(得分:0)

我不得不取消注释

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

在app / admin / game.rb