一对一DataMapper关联

编程入门 行业动态 更新时间:2024-10-28 15:20:57
本文介绍了一对一DataMapper关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I'm very new to DataMapper, and I'm trying to create models for the following scenario:

我有许多用户(使用用户名,密码等),它们也可以是玩家或裁判,或者两者都可以(因此,不能选择单表继承").基本模型为:

I've got a number of users (with a user name, password etc.), who can also be players or referees or both (so Single Table Inheritance is not an option). The base models would be:

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术语来说,我想我想要的是对球员"和裁判员"表中外键的唯一约束.

I'm not sure, though, what kinds of associations to add to Player and Referee. With belongs_to :user, multiple players can be associated with the same user, which doesn't make sense in my context. In RDBMS terms I guess what I want is a unique constraint on the foreign key in the Players and Referees tables.

如何在DataMapper模型中完成此操作?我必须在验证中亲自执行检查吗?

How do I accomplish this in my DataMapper model? Do I have to perform the check myself in a validation?

推荐答案

您可以通过不同的方式进行此操作.这是一个选择:

There are different ways you could do this. Here's one option:

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

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

Act on the referee/player models like:

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.

查看是否可行.我没有实际测试过,但是应该很好.

See if this works. I haven't actually tested it but it should be good.

更多推荐

一对一DataMapper关联

本文发布于:2023-10-26 14:37:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530432.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:DataMapper

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!