1

次の特性を持つアプリケーションがあります

There are Clubs
Each Club has Teams
Each Team has Players

ユーザーテーブルがあります。ユーザー テーブルには、基本的に、クラブ マネージャー、チーム マネージャー、およびプレーヤーがシステムにログインするためのユーザー名とパスワードが含まれています。

モデルとテーブルをどのように構成すればよいですか?

クラブ、チーム、選手のテーブルを作成する予定です。しかし、それらと users テーブルの間の関係を構造化する方法がわかりません。

user_idそれぞれのモデルで作成できましたが、その関係はClub belongs_to User正しくないようです。さらに、次のようなユーザーモデルになります

has_one :club
has_one :team
has_one :player

これは正しくありません。ユーザーは、いつでもそれらのうちの 1 つのみを持つことができます。

これを構造化するより良い方法はありますか?

4

1 に答える 1

1

Railsの下でhas_oneは、実際には「最大で1つ」です。has_oneに 3 つのデコレータすべてを含めることは完全に有効ですUser。正確に 1 つだけであることを確認したい場合は、次のように検証を追加できます。

class User < ActiveRecord::Base
  has_one :club
  has_one :team
  has_one :player

  validate :has_only_one

  private

  def has_only_one
    if [club, team, player].compact.length != 1
      errors.add_to_base("Must have precisely one of club, team or player")
    end
  end
end

データベースの users テーブルを変更できるので、 、 、をに入れclub_id、次のようにすると思います。team_idplayer_idusers

class Club < ActiveRecord::Base
  has_one :user
  has_many :teams
  has_many :players, :through => :teams
end

class Team < ActiveRecord::Base
  has_one :user
  belongs_to :club
  has_many :players
end

class Player < ActiveRecord::Base
  has_one :user
  belongs_to :team
  has_one :club, :through => :team
end

class User < ActiveRecord::Base
  belongs_to :club
  belongs_to :team
  belongs_to :player

  validate :belongs_to_only_one

  def belongs_to_only_one
    if [club, team, player].compact.length != 1
      errors.add_to_base("Must belong to precisely one of club, team or player")
    end
  end
end

User名前を、Managerまたはhas_one :manager, :class_name => "User"、およびモデルに変更したくなることさえありますが、あなたの呼び出し.ClubTeamPlayer

于 2010-08-24T12:32:00.240 に答える