锦标赛 - >团队 - >球员协会

时间:2017-03-05 10:43:58

标签: ruby-on-rails associations

我是Rails的初学者,但我正在学习。我正在尝试创建一个锦标赛入口门户网站,一个团队将进入一个特定锦标赛的球员。我已经对关联进行了一些阅读,但在这个例子中如何应用它们时遇到了一些麻烦。

作为基本概述:

  • 一场比赛,有很多球队。
  • 每支球队都有很多球员
  • 因此,一场比赛也有很多球员(通过球队 输入的)

这是我的代码,但我不确定它是否正确,因为我无法获得与玩家相关的任何锦标赛。

(tournament.rb)

class Tournament < ApplicationRecord
  has_many :teams
  has_many :players, :through => :teams  
end

(team.rb)

class Team < ApplicationRecord
  belongs_to :tournament
  has_many :players
end

(player.rb)

class Player < ApplicationRecord
  has_one :team
  has_one :tournament, :through => :team
end

在玩家表中,有team_id和amp; tournament_id字段,但是当我在控制台中尝试时,我只能通过关联填充team_id字段。

我想知道我的协会是否有什么不妥。

3 个答案:

答案 0 :(得分:0)

使用&#39; belongs_to&#39;,&#39; has_many&#39;,&#39; has_one&#39;当然取决于数据库中的数据模型。

如果在players表中有team_id外键,则需要将Player类定义为:

class Player < ApplicationRecord
  belongs_to :team
  has_one :tournament, :through => :team
end

另外,我真的相信锦标赛&lt; - &gt;团队应该有多对多的关联(如果团队当然可以参加很多比赛)。我建议添加模型TeamTournament并将最终模型结构定义为:

class Tournament < ApplicationRecord
  has_many :team_tournaments
  has_many :teams, :through => :team_tournaments
  has_many :players, :through => :teams
end

class TeamTournament < ApplicationRecord
  belongs_to :team
  belongs_to :tournament
end

class Team < ApplicationRecord
  has_many :team_tournaments
  has_many :tournaments, :through => :team_tournaments
  has_many :players
end

答案 1 :(得分:0)

Player类应该具有与Team和Tournament

的belongs_to关联
class Player < ApplicationRecord
  belongs_to :team
  belongs_to :tournament
end

答案 2 :(得分:0)

行。我假设您的问题与您的模型关联有关,而不是如何设置关联以从tournament_id获取player等等。因此,我将尝试向您提供有关您的项目的一些提示,并可以为其设置关联。

当我了解您的门户网站时...您希望tournament有多个teamsteam有多个players。但是,您希望从tournament_id获取player。我相信你不想这样做,因为在现实生活中,锦标赛确实可能“拥有”一些球员,但每个球员都不必属于某些锦标赛。他可以参加很多锦标赛。所以你不需要为此设置关联。锦标赛和球队也一样。但由于球队有球员,他必须属于那支球队。所以你需要关联。

为您设置我的设置就像:

(tournament.rb)

class Tournament < ActiveRecord::Base
  has_many :teams
end

(team.rb)

class Team < ActiveRecord::Base
  has_many :players
end

(player.rb)

class Player < ActiveRecord::Base
  belongs_to :team
end

关于如何在没有直接关联的情况下获得某些tournament参与的team的示例:

team = Team.first # just take some team
Tournament.includes(:teams).where(teams: { id: team.id })

您可以通过同样的方式实现其他目标(获得特定玩家所属的锦标赛等等)。但是这种情况不需要关联。当对象在概念上与另一个对象相关时,需要关联。

相关问题