2013-08-20 23 views

回答

2

我想這是你想要什麼:

class Event < ActiveRecord::Base 
    has_many :clients, :class_name => 'Contact', :foreign_key => 'client_id' 
    has_many :organizers, :class_name => 'Contact', :foreign_key => 'organizer_id' 
end 

來源:Rails Model has_many with multiple foreign_keys

1

可能不是你正在尋找的解決方案,但我認爲在這種情況下使用「Polymorphic Associations」將是合適的。

因此,您的Contact模型將是多態關聯模型,它將保留每行ClientOrganizer。然後

這些模型之間的關聯是:

class Event < ActiveRecord::Base 
    has_many :contacts 
end 

class Contact < ActiveRecord::Base 
    belongs_to :contactable, polymorphic: true 
    belongs_to :event 
end 

class Client < ActiveRecord::Base 
    has_many :contacts, as: :contactable 
end 

class Organizer < ActiveRecord::Base 
    has_many :contacts, as: :contactable 
end 

該模型的遷移將被:

class CreateContacts < ActiveRecord::Migration 
    def change 
    create_table :contacts do |t| 
     t.references :contactable, polymorphic: true 

     # Other contacts attributes 
    end 
    end 
end 
+0

+1超過繼承組成 – TheIrishGuy

相關問題