2011-06-03 233 views
0

我有一个用户模型,农民模型,医生模型和教育模型。Ruby on Rails模型/数据库协会

农民有一个用户和许多教育。

医生有一个用户和许多教育。

如何为教育模型设置数据库?

它应该有farmer_id和doctor_id吗?

但是教育不能同时属于农民和医生。它是一个或另一个。

因此,我的教育数据库条目要么填写farmer_id,要么填写doctor_id,但不能同时填写。

有没有办法保证一次只能填写其中一个ID?

或者是否有更好的方法来关联这些模型?

您的帮助将不胜感激!

哦,不要担心模型的名称(农民,医生等)。这只是一个例子。

回答

2

我看到了两种可能的解决方案。

第一个是利用多态关联进行教育。这可能是这样的:

class Farmer < ActiveRecord::Base 
    belongs_to :user 
    has_many :educations, :as => :profession 
end 

class Doctor < ActiveRecord::Base 
    belongs_to :user 
    has_many :educations, :as => :profession 
end 

class Education < ActiveRecord::Base 
    belongs_to :profession, :polymorphic => true 
end 

因此,而不是教育有doctor_id或farmer_id它有一个profession_id和一个profession_type。

第二个解决方案是使用单表继承。在您的情景中,可以通过让医生成为用户而不是属于用户来实现。当然对于农民来说也是一样的。这可能是这样的:

class User < ActiveRecord::Base 
    has_many :educations 
end 

class Farmer < User 
end 

class Doctor < User 
end 

class Education < ActiveRecord::Base 
    belongs_to :user 
end 

而且在这种情况下,你将一个类型列添加到用户模型来存储它是什么类型的类,然后只为在教育模式

+0

每当我在rails中使用STI时,我都非常后悔。我不知道这只是我是愚蠢的还是只是糟透了。我会选择多态关系解决方案。 – 2011-06-03 10:48:16

+0

Polymorphic可能也是我的选择。 – DanneManne 2011-06-03 11:05:47

+0

所以专业模型有一个profession_id和profession_type?两者都是数据库中的整数字段?我可以通过专业模型中的枚举来表示profession_type? – sizzle 2011-06-07 19:51:39

2

我认为它适合基于角色的这种关系。

Class User 
    has_one :role 
    has_many :educations 
end 

Class Role 
    #What ever roles you have. 
    #Farmer or Doctor 
    belongs_to :user 
end 


class Education 
    belongs_to :user 
end 

这样你就可以将user_id存储在教育对象中,它可以解决你的问题。

+0

您的评论为user_id “你有什么角色,农夫或医生。”这是否意味着我应该有,例如:'类医生belongs_to:用户端'或什么?我不明白。或者我应该有一个代表角色类型的枚举?那枚举将作为一个整数存储在角色表中? – sizzle 2011-06-07 20:00:00

+0

不一定,角色表中只有2条记录。角色将基本上有这些领域。 'Role.create(:name =>“Farmer”),Role.create(:name =>“Doctor”)'。然后你必须将角色对象的id存储在相应的用户对象中。'User.create(:role_id => what_ever_id_of_the_role,:all_your_fields)' – Deepak 2011-06-09 09:57:25