HABTM 多态关系 [英] HABTM Polymorphic Relationship
问题描述
我对 Rails 还很陌生,我正在尝试建立一个多态的 HABTM 关系.问题是我想要关联三个模型.
I'm pretty new to Rails, and i'm trying to do a polymorphic HABTM relationship. The problem is that I have three models that I want to relate.
第一个是事件模型,然后是两种参与者:用户和联系人.
The first one is the Event model and then are two kind of attendees: Users and Contacts.
我想做的是能够将用户和联系人作为参与者联系起来.所以,我现在的代码是:
What I want to do is to be able to relate as an attendee both users and contacts. So, what i have right now in my code is:
事件模型
has_and_belongs_to_many :attendees, :polymorphic => true
用户模型
has_and_belongs_to_many :events, :as => :attendees
联系方式
has_and_belongs_to_may :events, :as => :attendees
- HABTM 表迁移需要如何进行?我有点困惑,我没有找到任何帮助.
- 它会起作用吗?
推荐答案
不,你不能那样做,没有多态 has_and_belongs_to_many 关联这样的东西.
No, you can't do that, there's no such thing as a polymorphic has_and_belongs_to_many association.
您可以做的是创建一个中间模型.大概是这样的:
What you can do is create a middle model. It would probably be something like this:
class Subscription < ActiveRecord::Base
belongs_to :attendee, :polymorphic => true
belongs_to :event
end
class Event < ActiveRecord::Base
has_many :subscriptions
end
class User < ActiveRecord::Base
has_many :subscriptions, :as => :attendee
has_many :events, :through => :subscriptions
end
class Contact < ActiveRecord::Base
has_many :subscriptions, :as => :attendee
has_many :events, :through => :subscriptions
end
通过这种方式,订阅模型的行为类似于 N:N 关系中的链接表,但允许您对事件具有多态行为.
This way the Subscription model behaves like the link table in a N:N relationship but allows you to have the polymorphic behavior to the Event.
这篇关于HABTM 多态关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!