简体   繁体   English

Rails多态has_many关联

[英]rails polymorphic has_many association

Is it possible to have a polymorphic "has_many" association in rails? Rails中是否可以有一个多态的“ has_many”关联?

I had a table notifications which had a communication_method that could be either an email address or a phone number: 我有一个表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

now I want to have more than one communication method per notifications, is it possible? 现在我希望每个通知有一种以上的通讯方式,可以吗? (something like has_many :communication_methods, :polymorphic => true ) I guess I will also need a migration in oder to create a many to many table of notifications to communication methods (类似has_many :communication_methods, :polymorphic => true )我想我也将需要在oder中进行迁移以创建多对多的通信方法通知表

As I know Rails still have no support for polymorphic has_many associations. 据我所知,Rails仍然不支持多态的has_many关联。 I was solving this adding new intermediate model, which has polymorphic association. 我正在解决这个添加的具有多态关联的新中间模型。 For your case it can be like the following: 对于您的情况,可能如下所示:

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

So the migration for CommunicationMethodLink will look like this: 因此,CommunicationMethodLink的迁移将如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM