对于中间三关系模型,什么是好的设计?

时间:2009-05-07 14:02:44

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

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

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

主题|关系|对象

apple |比|更甜柠檬

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

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 = apple

relation =比

更甜蜜

object_id = 2

object_type = lemon

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

如何在apple,lemon和relation的模型类中设置关联?表格设计的关系是这样的吗?

非常感谢你的帮助!!

-Alex

2 个答案:

答案 0 :(得分:1)

给出你描述的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

答案 1 :(得分:0)

Polymorphic IS PAIN:

除非你需要它,否则使用像Single Table Inheritance:

这样的东西
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

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