【问题标题】:Two has_many_through Relationships To Same Model同一模型的两个 has_many_through 关系
【发布时间】:2013-09-26 18:43:29
【问题描述】:

我有一个Contributor 模型和一个Resource 模型。在一个简单的世界里,我会有以下设置:

class Resource

   has_many :authorships
   has_many :contributors, through: :authorships

end

class Contributor

   has_many :authorships
   has_many :resources, through: :authorships

end

但是,我的要求发生了变化。贡献者现在可以是资源的编辑者或资源的作者。 Contributor 可以是一个资源的 Editor 和另一个资源的 Author。所以看来我有两种方法来处理这个要求:

  1. 将某种is_editor? 属性添加到我的Authorships 连接模型并有效地注释每个关系。

  2. 创建第二个连接模型 – Editorship:

     class Resource
       has_many :authorships
       has_many :editorships
       has_many :contributors, through: :authorships
       has_many :contributors, through: :editorships
    
     end
    
     class Contributor
       has_many :authorships
       has_many :editorships
       has_many :resources, through: :authorships
       has_many :resources, through: :editorships
     end
    

哪种方法最明智,或者我还缺少其他方法吗?

【问题讨论】:

  • Rails 多态关联支持第一种情况,但我认为第一个问题是您是否需要/想要支持同时是作者和编辑的Contributor
  • EditorsAuthors 是相同的。它们在各个方面都可以互换。我不想子类化并建立多态关系,因为这感觉不对。在我看来,Join 更清楚地描述了这种关系。我最终也会有很多重复,因为相同的数据会同时表示为作者和编辑。
  • 我的问题是一个人是否可以成为同一资源的编辑和作者。
  • @PeterAlfvin 对不起。我误解了。我想这是可能的,尽管查看我的数据集并没有发生。贡献者当然可以是一个资源的编辑和另一个资源的作者,但我认为他们不太可能同时是同一资源的编辑和作者。

标签: ruby-on-rails ruby-on-rails-3 join model has-many-through


【解决方案1】:

鉴于您的说明,我将使用第一种方法,但您可能想要概括语言和概念,而不是仅仅为 Authorship 引入 is_editor 布尔值,而是使用 ResourceContributorship 和 @987654324 @ 字段,现在可以是 :author:editor,但将来可以扩展。

【讨论】:

  • 感谢您的回答。这是有道理的。
猜你喜欢
  • 2014-12-18
  • 1970-01-01
  • 1970-01-01
  • 2018-12-29
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
  • 2018-07-11
相关资源
最近更新 更多