【问题标题】:What's a good design for an intermediate triple-relation model?中间三元关系模型的好的设计是什么?
【发布时间】:2010-10-24 12:07:16
【问题描述】:

我是 Rails 新手,还没有掌握关联的所有可能性。这是我的问题:

我有几个模型,比如苹果和柠檬。 然后是包含三元组关系的模型“关系”:

主题 |关系 |对象

苹果 |比| 更甜柠檬

“关系”的迁移是这样的:

create_table :relations do |t|
  t.references :subject,  :polymorphic => true
  t.string     :relation
  t.references :object,   :polymorphic => true
  t.timestamps    
end

这应该存储类似的关系

subject_id = 1

subject_type = 苹果

关系 = 比

object_id = 2

object_type = 柠檬

实际上我有不止 2 个模型,所以我认为我需要通过使用多态选项使主题和对象列与模型无关。

您将如何设置苹果、柠檬和关系模型类中的关联?这样的关系表设计好不好?

非常感谢您的帮助!!

-亚历克斯

【问题讨论】:

    标签: ruby-on-rails database-design data-modeling modeling


    【解决方案1】:

    多态是痛苦的:

    除非您非常需要它,否则请使用 SingleTableInheritance 之类的东西:

    class Fruit < ActiveRecord::Base
       has_many :relations
       has_many :related_objects, :through => :relation, :class_name => 'Fruit'
       has_many :relating_subjects, :through => :relation, :class_name => 'Relation'
    end
    class Relation < ActiveRecord::Base
       belongs_to :object, :class => 'Fruit'
       belongs_to :subject, , :class => 'Fruit'
       validate_presence_of :object_id
       validate_presence_of :subject_id
       validate_presence_of :relation
    end
    

    然后喜欢:

    class Apple < Fruit
       ...
    end
    

    希望对你有帮助,(我没有测试过这段代码)

    【讨论】:

      【解决方案2】:

      给出您描述的 db 架构,看起来应该相当简单:

      class Relation < ActiveRecord::Base
        belongs_to :object, :polymorphic => true
        belongs_to :subject, :polymorphic => true
      end
      

      你的其他课程看起来像这样

      class Apple < ActiveRecord::Base
        has_many :object_relations, :class_name => 'Relation', :as => :object
        has_many :subject_relations, :class_name => 'Relation', :as => :subject
      end
      
      class Orange < ActiveRecord::Base
        has_many :object_relations, :class_name => 'Relation', :as => :object
        has_many :subject_relations, :class_name => 'Relation', :as => :subject
      end
      

      【讨论】:

      • 太棒了,这是我需要的 80% => 好的! (我的描述非常简化,真实情况是/更复杂)tha-hanx!
      猜你喜欢
      • 2017-06-15
      • 1970-01-01
      • 1970-01-01
      • 2013-07-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多