Rails关联,我该如何指定这种关系?

时间:2015-05-10 03:27:59

标签: ruby-on-rails activerecord rails-activerecord

操作系统:Windows 7 Rails:4.2.0

您好,如果我有两个型号,请说游戏团队

一个游戏可以有很多团队,但团队也可以属于很多游戏。

我似乎无法找到正确的方法来做到这一点,Belongs_to_many并不存在,而且我认为团队不会有很多游戏,游戏可以拥有多个团队。

5 个答案:

答案 0 :(得分:0)

has_and_belongs_to_many

我相信你需要的东西

答案 1 :(得分:0)

has_and_belongs_to_many

http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

或者您创建了一个加入模型(例如TeamMembership),即属于团队和游戏

答案 2 :(得分:0)

您想使用has_and_belongs_to_many关联。

您的模型应如下所示:

class Games < ActiveRecord::Base
  has_and_belongs_to_many :teams #append this line to your model
end

class Teams < ActiveRecord::Base
  has_and_belongs_to_many :games #append this line to your model
end

您还需要为游戏和团队创建一个连接表,如下所示:

class CreateGamesTeams < ActiveRecord::Migration
  def change
    create_table :gamess_teams do |t|
      t.integer :game_id
      t.integer :team_id
    end
  end
end

请记住运行rake db:migrate来创建此联接表。

答案 3 :(得分:0)

有两种方法可以解决这个问题:

  • 一个是@Alex Pan的回答:使用has_and_belongs_to_many
  • 另一个是与联结表使用belongs_tohas_many关系。
    • game.rb中:
      • has_many :game_team_maps
      • has_many :teams, through: :game_team_maps
    • {li> in team.rb
      • has_many :game_team_maps
      • has_many :games, through: :game_team_maps
      {li> in game_team_map.rb
      • belongs_to :game
      • belongs_to :team

在我看来,第二种方式更灵活,更易于维护。我选择它作为我自己的项目。

来自railscast的非常详细且有用的演员可帮助您解决此问题:http://railscasts.com/episodes/47-two-many-to-many

答案 4 :(得分:0)

虽然has_and_belongs_to_many肯定是一个有效选项,但我所知道的大多数“游戏”都有一个主队和一支客队,所以做一些像这样的事情可能是有道理的:

class Game < ActiveRecord::Base
  belongs_to :home_team, class_name: 'Team'
  belongs_to :away_team, class_name: 'Team'
end

class Team < ActiveRecord::Base
  has_many :home_games, class_name: 'Game', foreign_key: :home_team_id
  has_many :away_games, class_name: 'Game', foreign_key: :away_team_id
end

您还可以使用has_many :through

对其进行建模
class Game < ActiveRecord::Base
  has_many :team_games
  has_many :games, through: :team_games
end

class TeamGame < ActiveRecord::Base
  belongs_to :game
  belongs_to :team

  scope :home, -> { where(home: true) }
  scope :away, -> { where(home: false) }
end

class Team < ActiveRecord::Base
  has_many :team_games
  has_many :games, through: :team_games
  has_many :home_games, -> { TeamGame.home }, through: :team_games, source: :game, class_name: 'TeamGame'
  has_many :away_games, -> { TeamGame.away }, through: :team_games, source: :game, class_name: 'TeamGame'
end