gpt4 book ai didi

ruby - 一对一的 DataMapper 关联

转载 作者:数据小太阳 更新时间:2023-10-29 08:32:38 25 4
gpt4 key购买 nike

我是 DataMapper 的新手,我正在尝试为以下场景创建模型:

我有许多用户(有用户名、密码等),他们也可以是球员或裁判或两者兼而有之(因此单表继承不是一个选项)。基本模型是:

class User
include DataMapper::Resource
property :id, Serial
# Other user properties go here
end

class Player
include DataMapper::Resource
property :id, Serial
# Other player properties go here
# Some kind of association goes here
end

class Referee
include DataMapper::Resource
property :id, Serial
# Other referee properties go here
# Some kind of association goes here
end

DataMapper.finalize

不过,我不确定要为 Player 和 Referee 添加什么样的关联。使用 belongs_to :user,多个玩家可以与同一用户相关联,这在我的上下文中没有意义。在 RDBMS 术语中,我想我想要的是对 Players 和 Referees 表中外键的唯一约束。

我如何在我的 DataMapper 模型中完成这项工作?我是否必须自己在验证中执行检查?

最佳答案

您可以通过不同的方式来做到这一点。这是一个选项:

class User
include DataMapper::Resource
property :id, Serial
# Other properties...
has 1, :referee, :required => false
has 1, :player, :required => false
end

class Referee
include DataMapper::Resource
# DON'T include "property :id, Serial" here
# Other properties...
belongs_to :user, :key => true
end
class Player
include DataMapper::Resource
# DON'T include "property :id, Serial" here
# Other properties...
belongs_to :user, :key => true
end

对裁判/球员模型采取行动,例如:

u = User.create(...)
u.referee = Referee.create(...)
u.player = Player.create(...)

u.player.kick_ball() # or whatever you want to call
u.player.homeruns
u.referee.flag_play() # or whatever.

看看这是否有效。我还没有实际测试过,但应该不错。

关于ruby - 一对一的 DataMapper 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17050891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com