2

我对 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

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

如何在我的 DataMapper 模型中实现这一点?我必须在验证中自己执行检查吗?

4

2 回答 2

5

有不同的方法可以做到这一点。这是一个选项:

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.

看看这是否有效。我还没有实际测试它,但它应该是好的。

于 2013-06-13T19:01:36.663 回答
0

先前的答案除了:required => false不被has 1属性识别之外还有效。

这也令人困惑,因为对于has n属性,您可以new在属性上使用 right 或以其他方式将其视为集合。在您的示例中,您很想编写代码

u = User.create ...
u.referee.create ...

但是在这种情况下失败了,has 1因为属性是一个单一的值,它开始生命nil,所以你必须使用前面的答案指示的方法。此外,必须明确地将belongs_to关联设置为键有点令人困惑。

It does seem to execute validations and have the right association actions (so u.save will also save the referred-to Referee). I just wish it were more consistent between has n and has 1.

于 2014-03-17T02:57:07.910 回答