HABTM多态关系 [英] HABTM Polymorphic Relationship

查看:181
本文介绍了HABTM多态关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是pretty的新的Rails,我试图做一个多态HABTM关系。问题是,我有三个车型,我想有关。

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

我想要做的是能够涉及的与会者用户和联系人。那么,是什么我现在在我的code是:

事件模型

  has_​​and_belongs_to_many:参加者,多态=>真正
 

用户模型

  has_​​and_belongs_to_many:事件:为=> :参加者
 

联系型号

  has_​​and_belongs_to_may:事件:为=> :参加者
 

  1. 如何HABTM表迁移需要呢?我有点困惑,我发现在没有任何帮助。
  2. 难道是去上班?
解决方案

没有,你不能这样做,有没有这样的东西作为一个多态has_and_belongs_to_many关联。

你可以做的是建立一个中间模式。或许,这将是这样的:

 类认购<的ActiveRecord :: Base的
  belongs_to的:与会者,多态=>真正
  belongs_to的:事件
结束

类事件<的ActiveRecord :: Base的
  的has_many:订阅
结束

类用户的LT;的ActiveRecord :: Base的
  的has_many:订阅:如=> :与会者
  的has_many:事件:通过=> :订阅
结束

一流的联系与LT;的ActiveRecord :: Base的
  的has_many:订阅:如=> :与会者
  的has_many:事件:通过=> :订阅
结束
 

这种方式认购模型表现像A N链接表:N的关系,但可以让你拥有多态行为的事件

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:

Event Model

has_and_belongs_to_many :attendees, :polymorphic => true

User Model

has_and_belongs_to_many :events, :as => :attendees

Contact Model

has_and_belongs_to_may :events, :as => :attendees

  1. How the HABTM table migration needs to be? I'm a little confused and i have found no help on that.
  2. Is it going to work?

解决方案

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆