gpt4 book ai didi

ruby-on-rails-3 - 如何建模这个 rails 关系, "has two"?

转载 作者:行者123 更新时间:2023-12-04 05:04:19 27 4
gpt4 key购买 nike

想象一下游戏中的角色名册。

我需要让用户投票决定哪个字符计数器哪个字符并且能够将其保存在数据库中。
Batman is strong against SupermanBatman is strong against JokerBatman is weak against The Riddler
如何对两个相同类型的模型之间的这种关系进行建模? Batman, Superman and Joker都是同一模型类型的一部分 Superhero .

如果我要在 ASP.Net MVC 之类的东西上创建相同的系统,我会创建一个名为 Counterpicks 的表。并有两个字段 source_idtarget_id作为 int 字段并将它们用作 Superhero 的外键表。我需要创建一个 Counterpick RoR中的模型?

有什么建议吗?

最佳答案

看一下 A Guide to Active Record Associations 中关于 Self Joins 的段落(导轨指南)。您还需要一个自连接。

您的案例与 Rails Guides 上的示例之间的区别在于,您需要在 Superhero 中建立多对多关系。模型,而示例显示的是 has_many关系的类型。

Rails 中的两种多对多关联( has_and_belongs_to_manyhas_many through )都需要数据库中的连接表。 Counterpicks你提到的表正是一个连接表。

在你的情况下,它最终看起来有点像这样:

class Superhero < ActiveRecord::Base
has_and_belongs_to_many :losers, :class_name => "Superhero", :foreign_key => "winner_id"
has_and_belongs_to_many :winners, :class_name => "Superhero", :foreign_key => "loser_id"
end

关于ruby-on-rails-3 - 如何建模这个 rails 关系, "has two"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15722741/

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