【问题标题】:How to model this rails relationship, "has two"?如何建模这种rails关系,“有两个”?
【发布时间】:2013-03-30 19:42:32
【问题描述】:

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

我需要让用户投票决定哪个字符计数器哪个字符,并能够将其保存在数据库中。

Batman is strong against Superman

Batman is strong against Joker

Batman is weak against The Riddler


如何在两个相同类型的模型之间建模这种关系? Batman, Superman and Joker 都是同一模型类型 Superhero 的一部分。

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

有什么建议吗?

【问题讨论】:

    标签: ruby-on-rails-3 model model-associations


    【解决方案1】:

    查看A Guide to Active Record Associations(Rails 指南)中关于自我加入的段落。您还需要一个自我加入。

    您的案例与 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
    

    【讨论】:

      【解决方案2】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-08
        • 1970-01-01
        • 1970-01-01
        • 2017-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多