rails polymorphic has_many association

时间:2014-10-21 19:54:32

标签: ruby-on-rails activerecord associations rails-migrations

是否可能有多态" has_many"铁路协会?

我有一张notifications的表communication_method,可以是电子邮件地址或电话号码:

change_table :notifications do |t|
  t.references :communication_method, :polymorphic => true
end

class Notification < ActiveRecord::Base
  belongs_to :communication_method, :polymorphic => true
  belongs_to :email_address, foreign_key: 'communication_method_id'
  belongs_to :phone_number, foreign_key: 'communication_method_id'
end

module CommunicationMethod
  def self.included(base)
    base.instance_eval do
      has_many :notifications, :as => :communication_method, :inverse_of => :communication_method, :dependent => :destroy
    end
  end
end

class EmailAddress
  include CommunicationMethod
end

class PhoneNumber
  include CommunicationMethod
end

现在我希望每个通知都有多种通信方式,是否可能? (类似于has_many :communication_methods, :polymorphic => true)我想我还需要在oder中进行迁移,以便为通信方法创建多对多的通知表

1 个答案:

答案 0 :(得分:1)

据我所知,Rails仍然不支持多态has_many关联。我正在解决这个添加新的中间模型,它具有多态关联。 对于您的情况,它可能如下所示:

class Notification < ActiveRecord::Base
  has_many :communication_method_links
  has_many :email_communication_methods, :through => :communication_method_links, :class_name => 'EmailAddress'
  has_many :email_communication_methods, :through => :communication_method_links, :class_name => 'PhoneNumber'
  belongs_to :email_address, foreign_key: 'communication_method_id'
  belongs_to :phone_number, foreign_key: 'communication_method_id'
end

class CommunicationMethodLink < ActiveRecord::Base
  belongs_to :notification
  belongs_to :communication_methods, :polymorphic => true
end

module CommunicationMethod
  def self.included(base)
    base.instance_eval do
      has_many :communication_method_links, :as => :communication_method, :inverse_of => :communication_method, :dependent => :destroy
    end
  end
end

class EmailAddress
  include CommunicationMethod
end

class PhoneNumber
  include CommunicationMethod
end

因此,CommunicationMethodLink的迁移将如下所示:

create_table :communication_method_links do |t|
  t.references :notification
  t.references :communication_method, :polymorphic => true
end