1

레일에 다형성 "has_many"연관을 적용 할 수 있습니까? 레일 다형성 has_many 연관

내가 한 이메일 주소 또는 전화 번호가 될 수있는 communication_method을 가진 테이블 notifications :

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 

가 지금 알림 당 하나 개 이상의 통신 방법을 갖고 싶어, 그것은 가능하다? (something like has_many :communication_methods, :polymorphic => true) 나는 또한 통신을위한 많은 수의 통지 테이블을 생성하기 위해 이동이 필요하다고 생각한다.

답변

1

레일스는 여전히 다형성 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