2010-10-25 91 views
1

我有一個接觸模型,這包括姓名,地址,電話號碼等我如何模擬這些關係?

我應該have_one接觸的用戶模型。

我有一個客戶模型has_many聯繫人。

我有一個有很多聯繫人的生產者模型。

聯繫人只能是用戶,用戶和客戶,用戶和製作人,或者這三者的任意組合。我還需要確保當聯繫人鏈接到多個模型以確保數據完整性時,鏈接相同的聯繫人記錄。

我該如何創建關聯?

回答

1

這看起來像一個polymorphic association一個良好的應用:

class User < ActiveRecord::Base 
    has_one :contact, :as => :contactable 
end 

class Customer < ActiveRecord::Base 
    has_many :contacts, :as => :contactable 
end 

class Producer < ActiveRecord::Base 
    has_many :contacts, :as => :contactable 
end 

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

編輯

看來我沒看過的規格,一路過關斬將:)要使用多個相同的聯繫人相關聯用戶,客戶等,你可以使用一個has_many :through

class User < ActiveRecord::Base 
    has_one :user_contact, :dependent => :destroy 
    has_one :contact, :through => :user_contact 
end 

class Customer < ActiveRecord::Base 
    has_many :customer_contacts, :dependent => :destroy 
    has_many :contacts, :through => :customer_contacts 
end 

class Producer < ActiveRecord::Base 
    has_many :producer_contacts, :dependent => :destroy 
    has_many :contacts, :through => :producer_contacts 
end 

class UserContact 
    belongs_to :user 
    belongs_to :contact 
end 

class CustomerContact 
    belongs_to :customer 
    belongs_to :contact 
end 

class ProducerContact 
    belongs_to :producer 
    belongs_to :contact 
end 

class Contact < ActiveRecord::Base 
    has_many :user_contacts, :dependent => :destroy # might use 'has_one' here depending on your requirements 
    has_many :users, :through => :user_contacts 
    has_many :customer_contacts, :dependent => :destroy 
    has_many :customers, :through => :customer_contacts 
    has_many :producer_contacts, :dependent => :destroy 
    has_many :producers, :through => :producer_contacts 
end 

這給你一個三個關聯中的每一個的聯合表。通過向連接表添加行,每個聯繫人可以屬於三個其他模型中的一個,一個或多個。

+0

但是,聯繫人同時屬於用戶,客戶和製作人。有沒有這種聯繫只能與一種類型聯繫? – thargor 2010-10-25 18:58:49

+0

呃,是的,這是真的。看我的編輯。 – zetetic 2010-10-25 19:26:01