2014-03-12 31 views
1

考虑以下几点:在Rails has_many关系中,中介模型可以服务两个以上的其他模型吗?

class Physician < ActiveRecord::Base 
    has_many :appointments 
    has_many :patients, through: :appointments 
end 

class Appointment < ActiveRecord::Base 
    belongs_to :physician 
    belongs_to :patient 
end 

class Patient < ActiveRecord::Base 
    has_many :appointments 
    has_many :physicians, through: :appointments 
end 

如果一个人如此倾斜,可以在:appointments模型还服务于其他车型呢?例如,我的祖母希望使用一个网站预约她的:dentist,也可能是:dietitian(这是一家大医院)。我可以通过所有人的“中间人”:appointments来做到这一点,或者我必须为每个使用不同的模型?

我自己的应用程序没有使用这些示例,它们只是为了说明。另一个例子是,使用:selection不仅用于:likes而且还用于:follow-ees,例如在Facebook-Twitter联盟中。您选择让两个人都关注,并选择他们喜欢的内容。这可以在Rails中完成吗?

+1

您可能正在寻找多态关联:http://guides.rubyonrails.org/association_basics.html#polymorphic-associations – ChrisBarthol

回答

1

下面是你可能想要尝试的东西,但它也可能有助于指定你正在尝试建模的实际上,因为你的理论问题只能用理论解答来回答。真正的解决方案非常好!

RelatedModel1 
    has_many :related_model2s, through: :common_model 
    has_many :related_model3s, through: :common_model 
    has_many :related_model4s, through: :common_model 

CommonModel 
    belongs_to :related_model1 
    belongs_to :related_model2 
    belongs_to :related_model3 

RelatedModel2 
    has_many :related_model1s, through: :common_model 

RelatedModel3 
    has_many :related_model1s, through: :common_model 

RelatedModel4 
    has_many :related_model1s, through: :common_model 

在这种情况下,你很可能也说:

RelatedModel4 
    has_many :related_model3s, through: :common_model` 

换句话说,他们都有许多相互的,通过共同的模式。

相关问题