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_id
player_id
users
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"
、およびモデルに変更したくなることさえありますが、あなたの呼び出し.Club
Team
Player