26

我对 Rails 很陌生,我正在尝试建立多态 HABTM 关系。问题是我要关联三个模型。

第一个是事件模型,然后是两种参与者:用户和联系人。

我想做的是能够以与会者的身份将用户和联系人联系起来。所以,我现在在我的代码中拥有的是:

事件模型

has_and_belongs_to_many :attendees, :polymorphic => true

用户模型

has_and_belongs_to_many :events, :as => :attendees

联系方式

has_and_belongs_to_may :events, :as => :attendees
  1. HABTM 表迁移需要如何?我有点困惑,我没有找到任何帮助。
  2. 它会工作吗?
4

2 回答 2

65

不,你不能那样做,没有多态 has_and_belongs_to_many 关联这样的东西。

您可以做的是创建一个中间模型。它可能是这样的:

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

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.

于 2011-08-06T06:38:00.557 回答
0

Resolveu parcialmente.

It does solve the problem given the framework that we have at our disposal, but it adds "unnecessary" complexity and code. By creating an intermediary model (which I will call B), and given A -> B -> C being "A has_many B's which has_many C's", we have another AR Model which will load one more AR class implementation into memory once it is loaded, and will instantiate for the sole purpose of reaching C instances. You can always say, if you use the :through association, you don't load the B association, but then you'll be left with an even more obsolete model, which will only be there to see the caravan pass by.

In fact, this might be a feature that is missing from Active Record. I would propose it as a feature to add, since it has been cause of concern for myself (that's how I landed in this post hoping to find a solution :) ).

Cumprimentos

于 2012-09-07T09:22:26.490 回答