实施 Rails 中的许多逻辑的最佳方法是什么?

What is the best way to implement belongs to many logic in Rails?

例如,我有模型 Match 和模型 Player。我想要的是让Player能够参加很多场比赛。

所以它应该看起来像这样:

@match_first = Match.first
@match_last  = Match.last

@match_first.players
#player1, player3, player4
@match_last.players
#player1, player4, player5

两场比赛可以同时有相同的球员。

在您的匹配模型中:

  has_many: :players, through: :appearances

在您的播放器模型中:

  has_many: :matches, through: :appearances
class Appearance < ActiveRecord::Base
  belongs_to :match
  belongs_to :player

你可以在外观上有额外的属性,比如 'goals_scored'。 through 模型不必称为 Appearance...它可以是 Attendance 或 MatchPlayer 或 PlayerMatch,但您可以看到最后两个名称具有约束力,因为在这种关联之外您还可以看到一名球员出现的所有比赛英寸

Rails提供了两种实现多对多关系的方法。 @zoot 的回答描述的第一个是 has_many :through。如果关系本身就是一个模型(即需要额外的属性或验证),这是一个很好的选择。

如果两个实体之间的关系是直接的,以至于您真的不需要第三个模型,则可以使用 has_and_belongs_to_many 关联。

在您的匹配模型中:

has_and_belongs_to_many :players

在您的播放器模型中:

has_and_belongs_to_many :matches 

当您使用 has_and_belongs_to_many 时,您确实需要创建一个包含关系的连接 table。迁移(假设 Rails 的版本相对较新)可能如下所示:

class CreateJoinTableMatchesPlayers < ActiveRecord::Migration
  def change
    create_join_table :matches_players, :users do |t|
      t.index [:match_id, :player_id], unique: true
    end
  end
end

Active Record Associations 指南中有一节讨论了如何在这两种方法之间进行选择。