如何建立这种铁轨关系,“有两个”?

时间:2013-03-30 19:42:33

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

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

我需要让用户投票决定哪个角色可以在数据库中保存哪个角色。

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模型?

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

A Guide to Active Record Associations(Rails指南)中查看自我联接的段落。你需要的也是一个自我加入。

您的案例与Rails指南示例之间的区别在于您需要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

答案 1 :(得分:0)