[英]belongs_to has_one structure
I have an application which has the following characteristics 我有一个具有以下特征的应用程序
There are Clubs Each Club has Teams Each Team has Players
I have a users table. 我有一个用户表。 The user table basically contains the username and password for the club manager, team manager and the player to login to the system.
用户表基本上包含俱乐部经理,团队经理和球员登录系统的用户名和密码。
How should I structure the models and the tables? 我应该如何构造模型和表格?
I plan to create tables for Club, Team and Players. 我计划为俱乐部,团队和玩家创建表。 But I am not sure show to structure the relationship between them and the users table.
但是我不确定会显示出它们与用户表之间的关系。
I could create user_id
in each of the model, but the relationship would be Club belongs_to User
which doesn't seems right. 我可以在每个模型中创建
user_id
,但关系将是Club belongs_to User
,这似乎不正确。 Moreover I would end up with a User model that has the following 此外,我最终得到一个具有以下内容的用户模型
has_one :club
has_one :team
has_one :player
Which is not right. 这不对。 A user will have only one of them at any given time.
用户在任何给定时间将只有一个。
Is there a better way to structure this? 有没有更好的方法来构造它?
Under Rails, has_one
is really "has at most one". 在Rails下,
has_one
确实是“最多拥有一个”。 It's perfectly valid to have all three has_one
decorators in User
. 在
User
拥有所有三个has_one
装饰器是完全有效的。 If you want to ensure they only have precisely one, you could add a validation, for instance: 如果要确保它们只有一个,则可以添加一个验证,例如:
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
Since you have the ability to change the users table in the database, I think I would put club_id
, team_id
, player_id
in users
, and have the following: 由于您可以更改数据库中的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
I'd even be tempted to rename User
as Manager
, or have has_one :manager, :class_name => "User"
in the Club
, Team
and Player
models, but your call. 我什至会想将
User
重命名为Manager
,或者在Club
, Team
和Player
模型中具有has_one :manager, :class_name => "User"
,但是您可以打电话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.