Rails Active Record中的模型关联澄清

时间:2014-01-30 05:25:30

标签: ruby-on-rails

我想弄清楚如何最好地做我的模型关联。我有3张桌子。

玩家团队 teamplayers

我的大纲是玩家可以属于多个团队。一个团队可以拥有多个玩家,但是在我的teamplayers表中我有2个字段 teamid playerid (不包括主键ID)。

例如:

Player has id of 1000
team has id of 501

在teamplayers表中,将存储为:

 team_id    player_id
  501        1000

那么我如何在模型中设计关系 belongs_to has_many

4 个答案:

答案 0 :(得分:0)

以下应该做:

class Player < ActiveRecord::Base
  has_many :team_players
  has_many :teams, through: :team_players
end

class TeamPlayer < ActiveRecord::Base
  belongs_to :player
  belongs_to :team
end

class Team < ActiveRecord::Base
  has_many :team_players
  has_many :players, through: :team_players
end

答案 1 :(得分:0)

你希望has_many通过关联。

class Player < ActiveRecord::Base
  has_many :teamplayers
  has_many :teams, through: :teamplayers
end

class TeamPlayer < ActiveRecord::Base
  belongs_to :player
  belongs_to :team
end

class Team < ActiveRecord::Base
  has_many :teamplayers
  has_many :players, through: :teamplayers
end

http://guides.rubyonrails.org/association_basics.html

答案 2 :(得分:0)

您可以按照以下方式实现此目的:

class Team < ActiveRecord::Base
  has_many :team_players
  has_many :players, :through => :team_players
end

class Player < ActiveRecord::Base
  has_many :team_players
  has_many :teams, :through => :team_players
end

class TeamPlayer < ActiveRecord::Base
  belongs_to :player
  belongs_to :team
end

相应的迁移可能如下所示:

class CreateTeamPlayers < ActiveRecord::Migration
  def change
    create_table :teams do |t|
      t.string :name
      t.timestamps
    end

    create_table :players do |t|
      t.string :name
      t.timestamps
    end

    create_table :team_players do |t|
      t.belongs_to :player
      t.belongs_to :team
      t.timestamps
    end
  end
end

然后,如果您想要获取特定团队的玩家,请执行

@team = Team.first (do as per your requirement)
@team.players

另外,要获取球员的球队,

@player = Player.first (do as per your requirement)
@player.teams

H2H:) -

答案 3 :(得分:0)

这可以通过两种方式实现:

首先是:

class Team < ActiveRecord::Base
   has_and_belongs_to_many :players
end

class Player < ActiveRecord::Base
   has_and_belongs_to_many :teams
end

第二是:

class Player < ActiveRecord::Base
   has_many :teamplayers
   has_many :teams, through: :teamplayers
end

class TeamPlayer < ActiveRecord::Base
   belongs_to :player
   belongs_to :team
end

class Team < ActiveRecord::Base
   has_many :teamplayers
   has_many :players, through: :teamplayers
end