2009-06-06 90 views
2

我是RoR的新手 - 我有三个模型:Customer,JobNote。客户有工作,而客户和工作都可以有笔记。有没有一种特殊的方式来处理这种类型的关系在Rails中,或者它会工作,如果我只是与Note有正常的belongs_to关系?如何在Rails中建模“可以属于A或B”关系?

我关注是具有两个customer_idjob_id但只有一个单一的一个领域将永远不会用于单个记录(即特定的注意事项可以指一个作业或客户的笔记中的问题,但从来都),并且它不觉得好的数据库设计有一半的时间空列。

我在想这个,还是有什么不明白的东西?

回答

4

我建议使用多态关联,因为它更灵活,更易于实施。所需要的模型如下:

class Note < ActiveRecord::Base 
    belongs_to :notable, :polymorphic => true 
end 

class Customer < ActiveRecord::Base 
    has_many :notes, :as => :notable 
end 

class Job < ActiveRecord::Base 
    has_many :notes, :as => :notable 
end 

与移民

create_table :notes do |t| 
    t.references :notable, :polymorphic => {:default => 'Photo'} 
end 

有关多态关联的细节,我建议google

+0

我会看看多态关联;谢谢! – 2009-06-06 17:54:27

相关问题