Rails 外键设置问题
我刚刚(重新)开始使用 Rails,并且正在制作一个小纸牌游戏应用程序。我似乎无法弄清楚我的外键设置。
假设我有 4 个对象:
- 游戏
- 玩家
- 手
- 卡牌
游戏有很多玩家,玩家有很多手,而手牌也有很多牌。但这些牌也独立于手牌、玩家和游戏。
例如,我的数据库中有 6 张卡片(1 到 6)。在同一场游戏中,卡 3 可能在 2 名玩家手中。
我该如何为此设置我的密钥?我应该为“CardInHand”创建另一个对象来简化它吗?
I'm just (re)starting playing around with Rails and I'm making a little card game app. I cannot seem to figure out my Foreign Key setups.
Say I have 4 objects:
- Game
- Player
- Hand
- Card
A Game has many Players, which have many Hands which have many Cards. But the cards are also independent of a Hand, Player and Game.
For example, I have 6 Cards in my database (1 to 6). It is possible that Card 3 could be in 2 Players Hands in the same Game.
How can I set up my keys for this? Should I just create another object for "CardInHand" to simplify it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
卡牌和手牌之间的关系是经典的
拥有并属于许多
(HABTM)。当您有 HABTM 关系时,需要有一个表来管理配对(例如,hands_cards,其中只有 id 对),但不需要相应的模型。
(请注意,您需要创建一个迁移来自己生成hands_cards表;它不会自动创建。)
正如您所说,您确实可以选择创建一个单独的模型来表示手中的牌-- 这是一个
has_many :through
关系 -- 但只有当有特殊原因将该关系建模为具体对象时我才会这样做。The relationship between cards and hands is the classic
Has And Belongs To Many
(HABTM). When you have a HABTM relationship, there needs to be a table to manage the pairings (hands_cards, say, with just pairs of ids in it) but there need not be a corresponding model.(Note that you'll need to create a migration to generate the hands_cards table yourself; it won't be created automatically.)
You do have the option, as you say, to create a separate model to represent a card being in a hand -- this is a
has_many :through
relationship -- but I would only do that if there's a special reason to model that relationship as a concrete object.Rails 的标准最佳实践不是在数据库中使用外键,而是在模型上使用验证来确保数据的正确性。
正如另一个答案解释了您想要设置的内容。
The standard Best Practice for Rails is not to use foreign keys in the db, but to use validations on the model to ensure data correctness.
As the other answer explains what you'll want to set that up.